doufei1988 2017-05-10 10:47
浏览 71

无法将特定行插入数据库PHP MySQL JSON

I pulled the json into the php object and started putting data from that object into the database. I have 20 users in json and everyone succeded to go into the database except one which surname is O'Carolan. I think that error is in that single quote, smth about that. I read everything about sql injection and tried everything i found here on stackoverflow with the similar errors and still doesnt work. I tried with the PDO also and prepared statements and still doesnt work. Here I always get an error: 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 ' 'male')' at line 2. Also, when printing out the users from json it prints them properly and everything is ok there, just that 3rd user O'carolan wont go into to database. My json is at http://dev.30hills.com/data.json and my code is:

<?php

$servername = "localhost";
$username = "root";
$password = "";
$db = "30hills";

// Create connection
$conn = new mysqli($servername, $username, $password, $db);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$json_string = 'http://dev.30hills.com/data.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, false);

$elementCount  = count($obj);

for ($x = 0; $x < $elementCount; $x++) {

    $id = $obj[$x]->id;
    $firstname = $obj[$x]->firstName;       
    $surname = $obj[$x]->surname;

    //if (preg_match('/'.$special_chars.'/', $surname)){
    //  $surname = str_replace("'","",$surname);
    //}

    $age = $obj[$x]->age;
    $gender = $obj[$x]->gender;

    echo $id;
    echo " ";
    echo $firstname;
    echo " ";
    echo $surname;
    echo "<br>";


    mysqli_query($conn, "INSERT INTO user (`id`, `firstName`, `surname`, `age`, `gender`) 
                VALUES($id, '$firstname', '" . $surname . "', $age, '$gender')") 
                or die(mysqli_error($conn));

?>

  • 写回答

1条回答 默认 最新

  • dtlh12053 2017-05-10 11:48
    关注

    The answer is that age = null in json wont insert into database, must make that nullable into the table

    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)