duanhao1004 2012-12-26 03:35
浏览 47

PDO Ajax更新mysql数据库

I need help in this PHP Ajax updating mysql database using PDO. I wanted to update the database if a user checks the checkbox. Below is my code:

JS:

$('input[name=product_new]').click(function(){

    var chkbox_id = $(this).attr('alt');
    var chkbox_selected = $(this).is(':checked');

    if(chkbox_selected == true)
    {
        chkbox_selected = "checked";
    }
    else
    {
        chkbox_selected = "uncheck";
    }


    $.post({
            url: "../products_listing.php",
            type: "POST",
            data: {product_id: chkbox_id, product_new: chkbox_selected},
            cache: false,
            success: function(){}

           });

});

PHP page with PDO to update database:

$id = $_POST['product_id'];
$product_new = $_POST['product_new'];
if(isset($_POST['product_new']))
{
    try
    {
        $query = "UPDATE productinfo SET new_arrival=? WHERE id=?";
        $stmt_new_chkbox = $conn->prepare($query);
        $stmt_new_chkbox->bindParam(1, $product_new, PDO::PARAM_STR);
        $stmt_new_chkbox->bindParam(2, $id, PDO::PARAM_INT);
        $stmt_new_chkbox->execute();
    }
    catch(PDOException $e)
    {
        echo 'ERROR: ' . $e->getMessage();
    }
}

It was working when I use mysql but now I've changed it to use PDO, it won't work anymore. I can't find where went wrong. Thanks in advance guys.

Below is the old code from mysql_:

$id = mysql_real_escape_string($_POST['product_id']);
$product_new = mysql_real_escape_string($_POST['product_new']);
if(isset($_POST['product_new']))
{
    $upt_new=mysql_query("update products_list set new_arrival='$product_new' where id='$id'");
}

Ok! I know what's wrong already. The damn directory path. I took out ../ and it works! Kinda weird though.

Because my js file is in JS folder and products_listing.php is outside of the js folder. Isn't it supposed to be ../products_listing.php?

Can anyone tell me why it's not working which it is supposed to be?

Thanks in advance guys!

  • 写回答

1条回答 默认 最新

  • dongpeng7744 2012-12-26 05:44
    关注

    Just split your task into 2 parts: AJAX part and PDO part.

    First of all make sure that your PDO part works well. Make a mock $_POST array, and then start playing with PDO calling this script directly, without AJAX. Ask questions here, if something goes wrong. then, as you ret it to work, move to AJAX part, the same way - first, without PDO by just by sending data to server and verifying if it's correct.

    Solving 2 problems at once makes things a lot harder. Always split your task into separate parts and solve them one by one.

    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?