-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