【问题标题】:Upload data to database with JSON [closed]使用 JSON 将数据上传到数据库 [关闭]
【发布时间】:2020-08-02 00:08:00
【问题描述】:

如何使用 AJAX、JSON 和 PHP 将数据上传到数据库? 这是代码。

AJAX

    function saveToTheDB(ratedIndex) {
        $.ajax({
            url: 'fetch.php',
            method: 'POST',
            cache: 'false',
            dataType: 'json',
            data: {
                ratedIndex: ratedIndex
            },
            success: function(data) {
                console.log(data);
            },
            error: function(error) {
                console.log(error);
            }
        });
    }

PHP

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    require_once 'includes\dbh.inc.php';
    $rate = $_POST['ratedIndex'];
    if(isset($_GET['userid'])){
    if($db->query(" INSERT INTO `recipes_ratings` (`recipe_rating_id`, `recipe_id`, `user_id`, `rating`)
    VALUES (null, 3 , 8, '".$rate."')
    "))   
    }
    echo json_encode($rate);
}

我做错了什么? 有人可以帮我解决这个问题吗?非常感谢!

编辑

错误 I get back a full object

【问题讨论】:

  • 如果您提供更具体的错误详细信息会很好。
  • 对不起,我加了。

标签: php mysql json ajax


【解决方案1】:

作为响应点,您有语法错误,在这里我重构了您的代码以便工作。

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require_once 'includes\dbh.inc.php';
    $rate = $_POST['ratedIndex'];

    if (isset($_GET['userid'])) {
        if($db->query("INSERT INTO `recipes_ratings` (`recipe_rating_id`, `recipe_id`, `user_id`, `rating`) VALUES (null, 3 , 8, '".$rate."')")) {
            // implementation if query is successful
        } 
    }

    echo json_encode($rate);
}

JFYI:避免将输入变量直接放入查询中,应使用Prepared Statements

【讨论】:

  • 我试过了。同样...
  • 我已经编辑了我的答案,现在检查一下。
  • 谢谢!它工作(上传到数据库),但同样,我在控制台中得到一个对象,因为我添加了一个新行: $recipeid = $_GET['recipe_id'];
猜你喜欢
  • 1970-01-01
  • 2012-06-10
  • 1970-01-01
  • 2017-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
相关资源
最近更新 更多