dongsheng4679 2014-12-01 20:48
浏览 41

PHP在json对象发布的mysql中插入数据

I want to send some data from a jQueryMobil.listwidget via PHP to a mysql database.

I get and post my listitems like this:

function getItems()
{ 
        var listview_array = new Array();
        $( "#itemList li" ).each(function(index) {
            listview_el = new Object();
            listview_el.id = index;
            listview_el.name=$(this).text();
            listview_el.owner="owner";
            listview_array.push(listview_el);
        });
        var stringifyObject = JSON.stringify(listview_array);
        //alert(stringifyObject);
        $.ajax({
            type: "POST",
            dataType: 'json',
            url: "insert.php",
            data: { mydata: stringifyObject },
        });
        //showItems();

}

i want to add my json-object to a mysql database/table which exists. On my request my data is sent but the if(prepStmnt) never succeeds.

 <?php

    $con = new mysqli($servername, $username, $password, $dbname);
    if (!$con) {
      die('Could not connect: ' . mysqli_error($con));
    }

    echo "preps";
    if($preparedStatement = $con->prepare('INSERT INTO Einkaufsliste (item, owner) VALUES (:name, :owner)')){
        $preparedStatement->execute(json_decode($_POST["mydata"], true));
        $preparedStatement->close();
        echo "done";
    };

    $con->close();
    ?> 

Can you please tell my why no data is stored in my db?

  • 写回答

1条回答 默认 最新

  • douju6850 2014-12-01 21:16
    关注

    MySQLi does NOT support named parameters.

    if($preparedStatement = $con->[...snip...] (:name, :owner)')){
                                                ^^^^^^^^^^^^^
    

    That's outright illegal in MySQLi, so your prepare fails, and everything else just falls of the end of the script, because you have no error checking.

    $prepare = $con->prepare(...);
    if (!$prepare) {
       die(mysqli_error($con));
    }
    

    A proper mysqli prepared statement would be

    $stmt = $con->prepare('INSERT ... VALUES (?, ?)');
    

    Note the ? placeholders.

    Never EVER assume your query will suceed. Even if your sql actually is correct, there's a near infinite number of ways for the query to fail. Always assume failure, check for that failure, and treat success as a pleasant surprise.

    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大