簡體   English   中英

PHP PDO Mysql插入失敗,不引發異常或錯誤

[英]PHP PDO Mysql Insert fails, throws no exception or error

摘要:

我有一個函數,正在使用PHP在MySQL數據庫中設置鍵值對,該函數調用一個執行所有插入操作的實用程序函數。 我知道此實用程序功能可以工作(將其與其他功能一起使用),但是由於某些原因,它無法插入記錄。

令人困惑的部分是它不會引發PDO異常,我在連接函數中設置了正確的errmode,因此它使我感到困惑,為什么我沒有響應。

任何想法如何解決此問題或使其出錯?

在數據庫中具有ID並為其分配鍵/值的函數

function setCredit($id){
//sets credit bool
//table to insert
$table='accountMeta';
//key
$key="isCredit";
//key value
$value="Y";
//array that is generated to insert 
$valueArray=array("id"=>$id,"key"=>$key,"value"=>$value,"date"=>mysqlTime(currentDate()));
if (isset($id)){
    //run the insert if $id exists
    $results=insert($valueArray,$table);
    echo $results;

} else {
    //fail if $id doesn't exist
    $results="ERROR: Invalid Inputs";

}
return $results;}

進行插入的效用函數

function insert($array,$table){
//$array should be formatted like "column"=>"data",... etc
$columns="";
$values="";
//generate the insert statement
foreach ($array as $id=>$val){
    $columns.=$id.",";
    $columnBind.=":".$id.",";

}

    //cut off some extra commas after our foreach
$columns=rtrim($columns,",");
$columnBind=rtrim($columnBind,",");
    //get dat connection
$DBH=dbConn();

    //prep the PDO


$sql=$DBH->prepare("Insert into $table($columns) VALUES($columnBind)");

//bind each value in the PDO
foreach ($array as $id=>$val){
    $sql->bindValue(":$id",$val);   

}

try{
    //give'r a go
    $sql->execute();
    return "SUCCESS";
} catch (PDOExecption $e){
    //and if she says no:
    return "ERROR: Failed to Insert";
    logMessage("select ".$e->getMessage());
   }
}

數據庫連接功能

function dbConn(){
$dbName=confLine("databaseName");
$dbUser=confLine("databaseUser");
$dbPass=confLine("databasePass");
$dbAddress=confLine("databaseAddress");
try{
    $DBH=new PDO("mysql:host=$dbAddress;dbname=$dbName","$dbUser","$dbPass");
    $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
    echo "Err connecting to DB";
    logMessage("dbConn ".$e->getMessage());
    exit;
}
  return $DBH;
}

答案

出現了2個問題:

未設置PHP.ini以提供所需的錯誤詳細信息。 感謝@Phil,他在注釋中建議在php.ini文件中將display_errors = on設置為error_reporting = E_ALL。

此后,出現此錯誤:

致命錯誤:消息為“ SQLSTATE [42000]”的未捕獲的異常“ PDOException”:語法錯誤或訪問沖突:1064 SQL語法有錯誤; 檢查與您的MySQL服務器版本相對應的手冊以獲取在'key,value,date)VALUES('9','isCredit','Y','2014-09-21')'第1行附近使用的正確語法在/var/www/html/finance/PHP/utils.inc:133中的堆棧跟蹤:#0 /var/www/html/finance/PHP/utils.inc(133):PDOStatement-> execute()#1 / var / www / html / finance / PHP / functions.inc(116):insert(Array,'accountMeta')#2 /var/www/html/finance/PHP/setCredit.php(5):setCredit('9' )#3 {main}在第133行的/var/www/html/finance/PHP/utils.inc中引發

經過很短的查找錯誤之后,我發現我在mysql中使用了保留字。 完全顯而易見的是,我使用“ key”作為列名。 一旦我將列名更改為非保留名稱,插入就成功了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM