douyou2048 2017-11-06 16:21
浏览 114

Json数组不会将值放入数据库

Trying to put a $json array values into database but sadly it does not work for some reasons and i can't find it why. My first guess was it cause it maybe of varchar255 in mysql?

<?php
$json = '[
    {
        "order_id":123,
        "kases_id":12,
        "product_quantity":121,
        "product_name":"suns",
        "postage_adress":"garaazha",
        "barcode":"2131231"
    }
]';
//create a DB connection
$connect = mysqli_connect("localhost", "root", "", "qrbuddy");


$result = json_decode($json);
foreach($result as $key => $value) {
    if($value) {
        mysqli_query($connect, "INSERT INTO qrbuddy (order_id, kases_id, product_quantity, product_name, postage_adress, barcode, status) VALUES ($value->order_id, $value->kases_id,$value->product_quantity,$value->product_name,$value->postage_adress,$value->barcode, 0)");
    }
    mysqli_close($connect);
}
?>

My database:

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


CREATE TABLE `qrbuddy` (
  `order_id` int(11) NOT NULL,
  `kases_id` int(11) NOT NULL,
  `product_quantity` int(11) NOT NULL,
  `product_name` varchar(255) NOT NULL,
  `postage_adress` varchar(255) NOT NULL,
  `barcode` varchar(255) NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT '0'
) 
  • 写回答

1条回答 默认 最新

  • dongyo1818 2017-11-06 21:35
    关注

    Try like this:

    $result = json_decode($json);
    foreach($result as $key => $value) {
        if($value) {
            mysqli_query($connect, "INSERT INTO `your_DATABASE_NAME`.`qrbuddy` (`order_id`, `kases_id`, `product_quantity`, `product_name`, `postage_adress`, `barcode`, `status`) VALUES ({$value->order_id}, {$value->kases_id},{$value->product_quantity},{$value->product_name},{$value->postage_adress},{$value->barcode}, 0)");
    
        }
        mysqli_close($connect);
    }
    

    Recently I noticed that I need to specify the Database name as well in order for a query to work 100%.

    Edit: Forgot to specify, make sure you write your Database Name instead of your_DATABASE_NAME. Just making sure you won't waste to much time on this one :)

    Also, from my own experience writing the variables inside curly brackets {$variable}, gives you higher % that the query will work. (And it's easier to read anyway =)


    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 matlab求解平差
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办