Saving JSON string to MySQL database

前端 未结 3 498
一个人的身影
一个人的身影 2020-12-28 23:17

I have a JSON string with me

{\"name\":\"jack\",\"school\":\"colorado state\",\"city\":\"NJ\",\"id\":null}

I need it to be saved in the Dat

3条回答
  •  攒了一身酷
    2020-12-28 23:50

    We'll use json_decode json_decode documentation

    Also be sure to escape! here's how I would do it below...

    /* create a connection */
    $mysqli = new mysqli("localhost", "root", null, "yourDatabase");
    
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    
    /* let's say we're grabbing this from an HTTP GET or HTTP POST variable called jsonGiven... */
    $jsonString = $_REQUEST['jsonGiven'];
    /* but for the sake of an example let's just set the string here */
    $jsonString = '{"name":"jack","school":"colorado state","city":"NJ","id":null}
    ';
    
    /* use json_decode to create an array from json */
    $jsonArray = json_decode($jsonString, true);
    
    /* create a prepared statement */
    if ($stmt = $mysqli->prepare('INSERT INTO test131 (name, school, city, id) VALUES (?,?,?,?)')) {
    
        /* bind parameters for markers */
        $stmt->bind_param("ssss", $jsonArray['name'], $jsonArray['school'], $jsonArray['city'], $jsonArray['id']);
    
        /* execute query */
        $stmt->execute();
    
        /* close statement */
        $stmt->close();
    }
    
    /* close connection */
    $mysqli->close();
    

    Hope this helps!

提交回复
热议问题