PHP连接到SQL没有给出错误消息

时间:2015-05-12 19:23:08

标签: php sql ado

我正在尝试使用PHP连接到我的SQL数据库

$conn = new COM ("ADODB.Connection")

我正在尝试运行try / catch以确保在抛出错误的情况下我能够捕获错误。 所以我在页面上伪造一个错误,但不是给我一个错误,脚本只是在那一刻停止,页面不会继续。

我正在寻找一种确保显示或通知我问题的方法。类似于导致500页投掷的东西。

这就是我的脚本现在的样子。注意,我在insert语句中添加了一个额外的单引号只是为了导致错误,所以我可以测试它。 {后面的echo'未显示在页面上。

//create an instance of the  ADO connection object
$conn = new COM ("ADODB.Connection")
or die("Cannot start ADO");

//define connection string, specify database driver
$connStr = "PROVIDER=SQLOLEDB;SERVER=".$myServer.";UID=".$myUser.";  PWD=".$myPass.";DATABASE=".$myDB;
$conn->open($connStr); //Open the connection to the database

//declare the SQL statement that will query the database
$query =  "INSERT INTO dbo.EventOnlineAppsIndividual (EventId, FirstName, LastName, Address, City, [State], Zip, Email) VALUES (". $_POST['id'] .", ''" . $_POST['FirstName'] ."','". $_POST['LastName']."', '". $_POST['Address']."','".$_POST['City']."', '". $_POST['State']."', '". $_POST['Zip']."', '".$_POST['email'] . "')" ;
echo $query . "<br before:<br>";
var_dump($query);

//execute the SQL statement and return records
$rs = $conn->execute($query);
echo "after";

1 个答案:

答案 0 :(得分:0)

很抱歉不太了解这个问题。下面是try-catch块中的代码。如果执行方法失败,我会抛出错误。它将输出字符串&#39;查询未执行&#39;。

try{
//create an instance of the  ADO connection object
$conn = new COM ("ADODB.Connection")
or die("Cannot start ADO");

//define connection string, specify database driver
$connStr = "PROVIDER=SQLOLEDB;SERVER=".$myServer.";UID=".$myUser.";  PWD=".$myPass.";DATABASE=".$myDB;
$conn->open($connStr); //Open the connection to the database

//declare the SQL statement that will query the database
$query =  "INSERT INTO dbo.EventOnlineAppsIndividual (EventId, FirstName, LastName, Address, City, [State], Zip, Email) VALUES (". $_POST['id'] .", ''" . $_POST['FirstName'] ."','". $_POST['LastName']."', '". $_POST['Address']."','".$_POST['City']."', '". $_POST['State']."', '". $_POST['Zip']."', '".$_POST['email'] . "')" ;
echo $query . "<br before:<br>";
var_dump($query);

//execute the SQL statement and return records
$rs = $conn->execute($query);
if(!$rs) {
  throw new Exception('Query did not execute')
}
//This echo still wont be hit. unless you move it to the catch block.
echo "after";

}
catch (Exception $e) {
  echo $e->getMessage();
  exit();
}