PHP:无法将json字符串插入数据库

时间:2017-05-15 16:26:59

标签: php json

我是php的新手。我在$(date +\%Y \%m)发送一个json字符串。那个json字符串是产品的数组列表。我将从android发送到php webservice。当我在解码后var_dump我的数组时它显示为null。

这是我的代码

post

这是我的json字符串,我在帖子中以<?php $servername = "mysql.hostinger.in"; $username = "username"; $password = "password"; $dbname = "db_name"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $orderDetails = mysqli_real_escape_string($conn, $_POST['orderDetails']); $name = mysqli_real_escape_string($conn, $_POST['name']); $refNo = mysqli_real_escape_string($conn, $_POST['refNo']); $date = mysqli_real_escape_string($conn, $_POST['date']); $amount = mysqli_real_escape_string($conn, $_POST['amount']); $objs = json_decode($orderDetails, true); //var_dump($objs); $sql = "INSERT INTO tblOrder (name, refNo, date, quality, design, qty, pcs, amount) values ('$name', '$refNo', '$date', 'mix quality', 'mix design', '1250', '2', '$amount')"; mysqli_query($conn, $sql); $orderId = mysqli_insert_id($conn); if(is_array($objs) || is_object($objs)){ foreach($objs as $item) { $sql2 = "INSERT INTO tblOrderDetails (orderId, quality, design, shade, quantity, rate) VALUES ('$orderId', '".$item['qualityName']."', '".$item['designName']."', '".$item['name']."','".$item['pcs']."', '".$item['amount']."')"; mysqli_query($conn, $sql2); } } mysqli_close($conn); ?> 传递。

orderDetails

在android中我使用Volley Library在帖子中发送数据。

请建议我。

1 个答案:

答案 0 :(得分:2)

您在$_POST['orderDetails']上获得的JSON是有效的(假设它是您在问题结尾处发布的字符串)。

但是,您使用

使其失效
$orderDetails = mysqli_real_escape_string($conn, $_POST['orderDetails']);

您应首先使用

对其进行解码
$objs = json_decode($orderDetails, true);

然后在构建SQL字符串时将每个属性转义为foreach循环:

foreach($objs as $item) {
    $qualityName = mysqli_real_escape_string($conn, $item['qualityName'] );
    $designName  = mysqli_real_escape_string($conn, $item['designName'] );
    /* ... */

    $sql2 = "INSERT INTO tblOrderDetails (orderId, quality, design, shade, quantity, rate) 
       VALUES ('$orderId', $qualityName, $designName, ....... )";

    mysqli_query($conn, $sql2);
}

重要提示:

我们强烈建议您使用 prepared statements 而不是转义数据,然后通过加入字符串来构建查询。

它们使用起来非常简单,代码更易读,更不容易出错,也不会受到SQL注入。