Sedric Heidarizarei Sedric Heidarizarei -4 years ago 79
JSON Question

Update Columns of Table with First value of objects

I Have a json Array, And This is one row of my json Rows, How Can I Put

38
to
id38
Column and
39
to
id39
Column.. Automaticaly?
Please see This Photo

This is My Code:

<?php
$con=mysqli_connect("localhost","root","","array");
mysqli_set_charset($con,"utf8");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT `survey_answers`,us_id FROM `user_survey`";
if ($result=mysqli_query($con,$sql)){
while ($row = mysqli_fetch_row($result)){
$json = $row[0];
if(!is_null($json)){
//$json = preg_replace("!\r?\n!", "", $json);
$jason_array = json_decode($json,true);
$id = array();
foreach ($jason_array as $data) {
if (array_key_exists('id', $data)) {
$id[] = $data['id'];
}
}
$ids= implode(', \r\n',$id);
$sql1="update user_survey set id38='$ids' where us_id=".$row[1];
echo $sql1."<br>";
mysqli_query($con,$sql1);
}
}
}
mysqli_close($con);
?>

Answer Source

Try to do something like this:

     <?php
while ($row = mysqli_fetch_row($result)){
        $json = $row[0];
        if(!is_null($json)){                
    $jason_array = json_decode($json,true);
    $idv=array();
    foreach ($jason_array as $data) {

        if (array_key_exists('id', $data)) {
            $id =$data['id'];
            $idv[] = "id$id='$id'";
        }
    }
    $ids= implode(',',$idv);
    $sql1="update user_survey set $ids where us_id=".$row[1];
    echo $sql1."<br>";
    mysqli_query($con,$sql1);// run the sql
        }
}

DEMO

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download