【发布时间】:2015-12-09 14:49:50
【问题描述】:
我被分配了一个大学项目的错误处理任务,但我无法让它工作。我需要使用 Try catch 捕获 SQL 错误,并将用户重定向到显示错误的新页面 error.php。我知道这不是处理错误的最佳方式,但这正是教授想要的。
这是我试图在其中一个页面上捕获错误的示例:
<?php
$orderid = $_REQUEST['orderid'];
connectDB(); // database connections are defined in connect_to_DB.php
try{
$strSql2 = "SELECT `order_date`, `status_id`, `emp_id`,`cust_id` FROM `salesorder` WHERE `order_id`='" .$orderid. "'" ;
$result = @mysqli_query($db, $strSql2) // or die("SQL error: " . mysqli_error());
if($row = mysqli_fetch_array($result)){
$orderDate = $row["order_date"];
$orderStatus=$row["status_id"];
$empid = $row["emp_id"];
$custid=$row["cust_id"];
if(!$result){
throw new Exception(mysqli_error($db));
}
mysqli_free_result($result); // Always release the recordset memory resources
mysqli_close($db); // Always close the database connection
connectDB();
$sqlcount = "SELECT COUNT(order_id) AS numrows FROM orderitem WHERE order_id=".$_REQUEST['orderid'];
$resultcount = @mysqli_query($db,$sqlcount) // or die ("SQL error: ".mysqli_error());
if($rowcount= mysqli_fetch_array($resultcount)){
$orderamount = $rowcount['numrows'];
if(!$resultcount){
throw new Exception(mysqli_error($db));
}
mysqli_free_result($resultcount);
mysqli_close($db);
}
}
} catch (Exception $e){
// redirect to a php error page
header("Location: error.php?msg=" . $e->getMessage() . "&line=" . $e->getLine());
}
这是错误页面上的代码,error.php:
<?
print "Error message: " . $_GET["msg"];
if(isset($_GET["line"])){
print " - line number: " . $_GET["line"];
}
抱歉,不小心删除了这篇文章的结尾……现在第 66 行 if($row = mysqli) 的 if 语句有一个错误,我无法清除。在我开始添加错误处理之前,一切正常。
提前感谢您的帮助。
【问题讨论】:
-
问题是什么? (使用 urlencode 作为消息)
-
只要你用
@抑制输出,你就无法捕捉到东西 -
@JayBlanchard 我的印象是 @ 只是抑制了给定函数调用的消息,而不是错误本身
-
第 66 行之前的行中缺少分号。
-
if($row =应该是while,而不是if。我们不是在这里比较,也不是分配。我们正在遍历行。并为它重新排列你的牙套。
标签: php mysql error-handling