在mysql中插入数据先前定义的变量

时间:2013-09-01 01:11:22

标签: php mysql insert

我正在使用此代码从Json获取数据并将它们插入到mysql中。但是,它不会在数据库中插入任何记录。

    <?php  
    include("db.php");  
    $currsiteurl = 'http://graph.facebook.com/1597233119';  
     $graph = json_decode(file_get_contents($currsiteurl));  
     $id = $graph->id;  
     echo "id        : ".$id;   
     echo "<br>";
     $username = $graph->username;  
      echo "username : ".$username;  
      echo "<br>";
     $gender = $graph->gender;  
      echo "gender   : ".$gender;  
      echo "<br>";
       $locale = $graph->locale;  
         echo "locale   : ".$locale;  


        mysql_query("INSERT INTO users_data (id, username, gender, locale) 
         VALUES ('.$id', '.$username', '.$gender', '.$locale')");    
          ?>

任何人都可以告诉我错误的地方吗?

2 个答案:

答案 0 :(得分:0)

mysql_query("INSERT INTO users_data (id, username, gender, locale) 
     VALUES ('.$id', '.$username', '.$gender', '.$locale')");  

你正在创建一个单独的字符串(带有嵌入的变量),所以点''。不是必需的。

如果id或gender中的任何一个是数字字段,那么这可能是阻止数据插入的原因(带点)。 (如果它们是数字,它们也不需要周围的撇号。)

答案 1 :(得分:0)

除了安迪G所说的:

  1. 您应该使用预准备语句来确保您正在接收的数据被正确转义以避免SQL注入攻击:http://php.net/manual/en/pdo.prepared-statements.php

  2. 为了帮助调试查询,请在mysql_query语句之后添加echo mysql_error()以打印错误(或使用此处警告中提到的一种新的方法:http://us1.php.net/manual/en/function.mysql-error.php

相关问题