按顺序更新json导致mysql

时间:2015-04-23 08:45:10

标签: php mysql json

我实际上想要以相同的顺序更新mysql。我有一个数据库,其中一些数据已经存在,并且sendondate是常见的。我试图更新但它只更新最后一个输出而不是所有序列。请帮帮我..

<?php
    $data = '[{"message":"Hello+Test+Message","sender":"test","billcredit":"0.00","messageStatus":"DND","sendondate":"2015-04-23 12:27:00","provider":"aaaa"},{"message":"Hello+Test+Message","sender":"test","billcredit":"0.00","messageStatus":"DELIVERD","sendondate":"2015-04-23 12:27:00","provider":"aaaa"}]';


       // $objs = json_decode($data);
    $con=mysqli_connect("localhost","root","Password*9","sms9");
        $objs = json_decode($data,true);
        foreach ($objs as $obj){
            $repor = $obj['messageStatus'];
           // echo $repor . '<br />';
            $sen= $obj['sendondate'];
            //echo $sen;

            $repor=array();
            while($row = mysql_fetch_array($repor))
        {
            $sql2=  "Update detail SET Delivery='$repor' WHERE Datetime='$sen'";
    if(mysqli_query($con, $sql2)){
            echo "up";
            }
        }

        }   

    ?>

1 个答案:

答案 0 :(得分:0)

只需删除$repor=array()while条件(我看不到,它的用途是什么):

<?php

$data = '[
   {"message":"Hello+Test+Message","sender":"test","billcredit":"0.00","messageStatus":"DND","sendondate":"2015-04-23 12:27:00","provider":"aaaa"},
   {"message":"Hello+Test+Message","sender":"test","billcredit":"0.00","messageStatus":"DELIVERD","sendondate":"2015-04-23 12:27:00","provider":"aaaa"}
]';

// $objs = json_decode($data);
$con = mysqli_connect("localhost","root","Password*9","sms9");
$objs = json_decode($data,true);

foreach ($objs as $obj) {
    $repor = $obj['messageStatus'];
    // echo $repor . '<br />';
    $sen = $obj['sendondate'];
    //echo $sen;

    $sql2 = "Update detail SET Delivery='$repor' WHERE Datetime='$sen'";
    if (mysqli_query($con, $sql2)) {
       echo "up";
    }
}

根据您的评论进行更新:

在sql中如果要修改特定行,则必须使用适当的where条件匹配它们。通常,根据非唯一列(如datetime)选择行不是一个好主意。因此,如果您可以更改db和json数据,通常的方法是定义某种id(通常是整数):

$data = '[
   {"id": 123, "message":"Hello+Test+Message","sender":"test","billcredit":"0.00","messageStatus":"DND","sendondate":"2015-04-23 12:27:00","provider":"aaaa"},
   {"id": 666, "message":"Hello+Test+Message","sender":"test","billcredit":"0.00","messageStatus":"DELIVERD","sendondate":"2015-04-23 12:27:00","provider":"aaaa"}
]';
...
    $id = $obj['id'];
    ...
    $sql2 = "Update detail SET Delivery='$repor' WHERE id=$id";

或者,如果您无法添加额外的列,则必须添加已定义的列以区分具有相同日期时间的行,例如发件人(发件人的值必须不同,以便记录区分它们,这是不是你的json样本数据的情况,但这只是用法的例子):

   ...
   $sender = $obj['sender'];
   ...
   $sql2 = "Update detail SET Delivery='$repor' WHERE Datetime='$sen' AND sender='$sender'";

额外的安全提示: 通常,您应该在发送到数据库之前正确escape数据,以防止sql injection。或者,您可以将prepared statementsbinded parameters一起使用。