SQL statement in PHP behaves differently than SQL

2019-03-03 23:27发布

I have

$form_store_sql = "                                                                                                                    
     INSERT INTO myodyssey_myaccount (`id`, `email`, `username`, `password`) VALUES (NULL, 'email', 'unixmiah.formtest', 'woohoo');         

     SET @last_id_in_myaccount = LAST_INSERT_ID();                                                                                      

     INSERT INTO myodyssey_personal_info (`id`, `myodyssey_myaccount_id`) VALUES (NULL, @last_id_in_myaccount);                             

    SET @last_id_in_personal_info = LAST_INSERT_ID();                                                                                  

    INSERT INTO myodyssey_travel_info (`id`, `myodyssey_personal_info_id`)                                                                 
        VALUES (NULL, @last_id_in_personal_info);                                                                                                      

     SET @last_id_in_travel_info = LAST_INSERT_ID();                                                                                    

     INSERT INTO myodyssey_tour_orders (`id`, `myodyssey_travel_info_id`) VALUES (NULL, @last_id_in_travel_info);";

     if(mysql_query($form_store_sql)){
       echo "done";
     }

It doesn't work; it doesn't store the data. But if I take the SQL statement out of the form_store_variable and paste it into phpmyadmin's sql dialog, it behaves differently, it stores the data. I wonder what I'm doing wrong storing the SQL statement in the form_store_variable.

2条回答
不美不萌又怎样
2楼-- · 2019-03-03 23:42

mysql_*() functions do NOT allow multiple statements like that in a single query call. It's a basic defense against some forms of SQL injection attacks.

If you'd used any kind of error handling on your query call, you'd have been informed of the syntax error:

$result = mysql_query($form_store_sql);
if ($result === false) {
   die(mysql_error());
}

You will have to query() each of those individual statements separately.

查看更多
Anthone
3楼-- · 2019-03-03 23:56

mysql_query() doesn't allow multiple queries in a single call. You need to split up $form_store_sql into separate strings for each query, and call mysql_query() separately for each of them.

$sql = "INSERT INTO myodyssey_myaccount (`id`, `email`, `username`, `password`) 
        VALUES (NULL, 'email', 'unixmiah.formtest', 'woohoo');";
mysql_query($sql);
$sql = "SET @last_id_in_myaccount = LAST_INSERT_ID();";
mysql_query($sql);
...

You can also avoid doing a separate call just to set a variable to LAST_INSERT_ID(), by just using that function in the next insert:

$sql = "INSERT INTO myodyssey_personal_info (`id`, `myodyssey_myaccount_id`)
        VALUES (NULL, LAST_INSERT_ID());"
mysql_query($sql);
查看更多
登录 后发表回答