2016-10-28 43 views
1

[ASK] 我的php錯誤「失敗的查詢您的SQL語法中有錯誤;請查看與您的MariaDB服務器版本對應的手冊,以獲取正確的語法(iduser,idfood,jumlah,total)VALUES(9,1,2,20000)'在第1行「 什麼是錯誤....?失敗的查詢您在SQL語法中遇到錯誤

myphp

<?php 
$data= file_get_contents('php://input'); 
    $array = json_decode($data, true); 

    require_once ('..../db_connectfood.php'); 

    $db = new DB_CONNECT(); 

    foreach($array as $row) 
    { 
     $idusr = $row["iduser"]; 
     $idfd = $row["idfood"]; 
     $jml = $row["jumlah"]; 
     $total = $row["total"]; 
     $result = mysql_query("INSERT INTO order (iduser, idfood, jumlah, total) VALUES ($idusr, $idfd, $jml, $total)") or die ("Failed query ".mysql_error());   

    } 
    if ($result) { 
     // successfully inserted into database 
     $response["success"] = 1; 
     $response["message"] = "successfully created."; 

     // echoing JSON response 
     echo json_encode($response); 
    } else { 
     // failed to insert row 
     $response["success"] = 0; 
     $response["message"] = "Oops! An error occurred."; 

     // echoing JSON response 
     echo json_encode($response); 
    } 

?> 

如何得到這個PHP的成功價值和消息?

enter image description here

ID用戶和idfood是外鍵

+1

您的表是否有名爲「iduser」的列?如果你從一個MySQL管理器執行該查詢,它是否工作? – Jason

回答

0

你好,請嘗試使用此:

$結果= mysql_query(「INSERT INTO databasename.order(ID用戶,idfood,jumlah,總計)VALUES ($ idusr,$ idfd,$ jml,$ total)「)或die(」Failed query「.mysql_error());

訂單是來自mysql的命名單詞。

此致敬意。

+0

感謝它的工作 –

1

order是SQL中的保留字。最好的辦法是改變你的餐桌名稱(例如,複數爲orders)。如果這是不可能的,你可以使用反引號逃脫名稱:

INSERT INTO `order` (iduser, idfood, jumlah, total) 
VALUES ($idusr, $idfd, $jml, $total) 

強制性評論:
在SQL語句中使用的字符串操作讓你的代碼容易受到SQL注入式攻擊。您應該考慮使用prepared statement

+0

擊敗了我。 :) – Shef

+0

感謝它的工作 –

0

orderreserved word

爲了能夠在查詢中使用保留字,必須通過在`保留字'中使用反引號將其包圍來避免它(注意反引號可能看起來像單引號,但不是)。

所以,你的情況變化

$result = mysql_query("INSERT INTO order (iduser, idfood, jumlah, total) VALUES ($idusr, $idfd, $jml, $total)") or die ("Failed query ".mysql_error()); 

$result = mysql_query("INSERT INTO `order` (iduser, idfood, jumlah, total) VALUES ($idusr, $idfd, $jml, $total)") or die ("Failed query ".mysql_error()); 

...並檢查表或列名的其餘部分,如果它們是保留字。

作爲最佳的&安全實踐,建議使用參數化查詢/準備語句。

+0

感謝它的工作 –

+0

@SomaKun:我很高興它幫助。隨意[**接受您的問題**的答案之一](http://meta.stackexchange.com/a/5235/165614)。 – Shef