PHP - MySQL事务执行错误

时间:2011-07-26 18:09:36

标签: php mysql transactions

    $tran = "START TRANSACTION;";  

    $tran_res = mysql_query($tran);  

    $qry_1 = "INSERT INTO docList (doc_ip , doc_country , doc_ref) VALUES ('$ip' , '$country' , '$http_ref');";  
    $res_1 = mysql_query($qry_1);  
    if(!$res_1)
        die ("qry1 fail " . mysql_error() );  

    $ins_id = mysql_insert_id();  
    if(!$ins_id) 
        die ("ins id fail " . mysql_error() );  
    echo "<b>$ins_id</b>";  

    $qry_2 = "INSERT INTO docContent (doc_id , cont_date , cont_title , cont_aim , cont_obj , cont_theory , cont_sw , cont_code) VALUES ('$ins_id' , '$dt' , '$title' , '$aim' , '$obj' , '$th' , '$sw' , '$code');"; 

    $res_2 = mysql_query($qry_2);  
    if(!$res_2)
        die("qry2 fail " . mysql_error() );  `

执行上述操作会返回以下错误:

2 qry fail You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'login'); if($query->num_rows()>0) return $query->result_array(); } ' at line 1

实际上$qry_2的执行失败了,但我对它所显示的错误感到困惑(错误说明中提到的第1行没有这样的代码)。此外,查询($qry_2)在MySql控制台中正确执行。

2 个答案:

答案 0 :(得分:2)

输出$qry_2的内容以查看要执行的实际SQL语句。很可能你有SQL注入漏洞,你插入的变量之一至少包含',导致语法错误。

e.g。如果你有

$var = "O'Reilly";
$sql = "INSERT INTO names (name) VALUES ('$var')";

你最终会得到

INSERT INTO names (name) VALUES ('O'Reilly');

将被解释为:

'O' - string containing the letter "O"
Reilly - a field named "Reilly", with no operator between this "field" and the "O" previous
'); - a weird unterminated string, also with no operator between this and the previous field.

要解决此问题,您必须通过mysql_real_escape_string()传递您的变量,这样可以防止此类错误发生。它会将O'Reilly变为O\'Reilly,这在您的查询中是“安全的”。

答案 1 :(得分:1)

您尚未发布MySQL服务器收到的真实查询,但我敢说您没有使用mysql_real_escape_string()将数据注入SQL中。

(您是否尝试在数据库中插入PHP代码?)