使用字符串mysql更新表

时间:2014-05-05 13:51:48

标签: php mysql sql string web-services

我有来自服务器的字符串响应:

string '{"code":1,"status":200,"data":
[{"connect_id":"3","equipment_id":"1","sample_id":"33","test_id":"44","message_type":"test_ordered","sent_date":"0000-00-00"},
{"connect_id":"12","equipment_id":"34","sample_id":"234","test_id":"234","message_type":"asdasd","sent_date":null}]}'

我必须使用"data"中的值更新本地表格的字段。 如果来自响应的值为NULL(来自" data"的特定字段),则在更新本地表时不应对该字段进行任何更改。

要更新的表格有很多字段,但我们只想更新以下三个字段:equipment_id,sample_id,test_id

更新成功后,我必须向服务器发回一个响应,告诉该事务已成功并更新它status(这是表的服务器的一个字段)从收集数据的位置发送响应),以便服务器不会发送两次响应。

1 个答案:

答案 0 :(得分:0)

我假设您在变量$ dbc中使用PDO和有效的pdo连接。我进一步假设你通过connect_id识别你的行。你应该根据你的需要改变它。

以下代码应该概述如何解决这个问题。请看我的评论。我没有为你完成所有工作,特别是省略了错误处理。

$result = json_decode($response, true);
// You should validate that the decoding was successful and
// that the result contains all the data you expect.

// You find your data as in $result['data']
// This is an (numbered) array of associative arrays with your "columns" as key
// and the data as value

// prepare your update statement
$q = $dbc->prepare('
    UPDATE mytable 
    SET 
        equipment_id = ?, 
        sample_id = ?, 
        test_id = ?
    WHERE
        connect_id = ?
    ');
foreach ($result['data'] as $row) {
    // and execute it while looping through the data-array with
    // the appropriate data. Please note that the order of the
    // parameters got to be the same as in the prepared statement
    $params = array(
        $row['equipment_id'], 
        $row['sample_id'], 
        $row['test_id'],
        $row['connect_id']
    );
    $q->execute($params);
    // check success of the execute too.
}