开发者

How could a query fail to insert data into mysql that is retrieved from WEB?

I need to insert some data into mysql. I am not sure if I need to check the inputs OR format/strip them before they could be inserted into database fields as results returned from web m开发者_如何学编程ay contain characters that mysql do not accept(I think). I have trouble with inserting tweets into mysql table. The type of field is varchar. This is insert statement in php script:

$json = $_POST['msg_top'];
      $msg = json_decode($json);
           foreach($msg->entry as $status)
               {
                 $t = $status->content;
                 $query = "INSERT INTO msg2(id,msg,msg_id,depth) VALUES ('','$t','ID','3')";
                 mysql_query($query);
                 if(!mysql_query($query, $dbh))
                 {die('error:' .mysql_error());} 
              }


Yes, it's very important to escape all values before using them in an SQL command.

$json = $_POST['msg_top'];
$msg = json_decode($json);
foreach($msg->entry as $status) {
    $t = mysql_real_escape_string($status->content);
    $query = "INSERT INTO msg2(id,msg,msg_id,depth) VALUES ('','$t','ID','3')";
    mysql_query($query);
    if( !mysql_query($query, $dbh) ) {
        die('error:' .mysql_error());
    }
}

Also, other possible issues with your query:

  1. If the id field is auto_increment'ing, you don't need it in the field or value list.
  2. I may be missing something, but why are you using the string 'ID' for the msg_id field?

As for help troubleshooting this, I'd recommend just appending all of the $query strings to a log file for later inspection. Then, if problems aren't readily apparent, you can just manually try to run the command on the database (ie: maybe via PhpMyAdmin) and check out any error codes from there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜