-1
我对这个查询很困难,并且建议我学习尝试并捕获块,以便更容易地找出错误。所以这是我的第一次尝试。尝试用预先准备好的语句来捕获
我得到了我的@ stmt2没有被定义为我的print_r($stmt2)
行的错误。
Notice: Undefined variable: stmt2
这是我在try try上的尝试。我为这个错误出现了什么问题吗?
try {
$con = mysqli_connect("localhost", "", "", "");
if (mysqli_connect_errno()) {
throw new Exception("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$cid = $_GET['cid'];
$tid = $_GET['tid'];
$userid = (isset($_SESSION['user']) ? $_SESSION['user'] : "");
//Prepare
if($stmt = mysqli_prepare($con, "SELECT * FROM forum_topics WHERE `category_id`=? AND `id`=? LIMIT 1")) {
mysqli_stmt_bind_param($stmt, "ii", $cid, $tid);
mysqli_stmt_execute($stmt);
/* fetch value */
mysqli_stmt_fetch($stmt);
if (!$stmt) {
throw new Exception($con->error);
}
}
$stmt->store_result();
$numrows = $stmt->num_rows;
if($numrows == 1){
echo "<table width='100%'>";
if ($_SESSION['user']) {
echo "<tr><td colspan='2'><input type='submit' value='Add Reply' onclick=\"window.location =
'forum_post_reply.php?cid=".$cid."$tid=".$tid."'\"> <hr />";
} else {
echo "<tr><td colspan='2'><p>Please log in to add your reply</p><hr /></td></tr>";
}
/*}
catch (Exception $e)
{
//print_r($e);
echo "There has been an error with the $stmt block.";
}
print_r($stmt);
try {*/
foreach($stmt as $row) {
//Prepared SELECT stmt to get forum posts
if($stmt2 = mysqli_prepare($con, "SELECT * FROM forum_posts WHERE `category_id`=? AND `topic_id`=?")) {
//var_dump($stmt2);
mysqli_stmt_bind_param($stmt2, "ii", $cid, $tid);
mysqli_stmt_execute($stmt2);
}
while (mysqli_stmt_fetch($stmt)) {
echo "<tr><td valign='top' style='border: 1px solid #000000;'>
<div style='min-height: 125px;'>".$row['topic_title']."<br />
by ".$row2['post_creator']." - " .$row2['post_date']. "<hr />" . $row2['post_content'] ."</div></td>
<td width='200' valign='top' align='center' style='border: 1px solid #000000;'>User Info Here!</td></tr>
<tr><td colspan='2'><hr /></td></tr>";
}
}
} else {
echo "<p>This topic does not exist.</p>";
}
}
catch (Exception $e)
{
//print_r($e);
echo "There has been an error with the foreach $stmt2 block.";
}
print_r($stmt2);
嗯,我想知道如果我做正确的try/catch语句,为什么我得到的错误,我的'$ stmt2'变量不定义。 – Paul
您收到关于您的$ stmt2变量的错误,因为它在catch语句中被硬编码。使用$ e-> getMessage()将处理第一个让你脱离正常脚本流程的异常。 – rotvulpix
你能否进一步解释或告诉我你的意思?仍试图学习try/catch。 – Paul