php - 脚本添加不起作用

标签 php mysql asp.net-web-api

简介

我正在尝试制作一个 API。从数据库读取工作正常... 然而写入失败。

奇怪的是,当我复制查询 error_log 打印输出并将其粘贴到 PHPMyAdmin 中时,它正确添加了对象。

代码

index.php

...
 else if($tag == 'addIngredient'){
    $name = $_POST['name'];
    $cal = $_POST['cal'];
    $fat = $_POST['fat'];
    error_log("name=".$name." cal=".$cal."fat=".$fat);
    if(!$db->addIngredient($name,$cal,$fat)){
        $response["error"] = TRUE;
        $response["error_msg"] = "addIngredient failed";
    }

 }
...

BDFunctions.php

...
public function addIngredient($name, $cal, $fat){
    $query= "INSERT INTO `ingredient` (`name`, `cal`, `fat`) VALUES('".$name."', ".$cal.", ".$fat.");";
    error_log($query);
    $result = mysql_query($query);
    if($result){return true;}
    return false;
}
...

我在我的 apache 日志中得到这些打印输出:...

[Wed Apr 29 20:46:58 2015] [error] [client 192.168.1.9] name=testName cal=50fat=20 [Wed Apr 29 20:46:58 2015] [error] [client 192.168.1.9] INSERT INTO ingredient (name, cal, fat) VALUES('testName', 50, 20);

最佳答案

你应该在其中的某个地方捕获mysql_error()。我还添加了 sprintf() 来帮助更好地准备语句。另外,我没有看到任何对您的数据库链接的引用($link$con 等)

public function addIngredient($name, $cal, $fat){
    $query= sprintf("INSERT INTO `ingredient` (`name`, `cal`, `fat`) VALUES ('%s', %d, %d);",
       $name,
       $cal,
       $fat
    );
    error_log($query);
    $result = mysql_query($query);
    if($result){return true;}
    error_log(mysql_errno($link) . ": " . mysql_error($link));
    return false;
}

关于php - 脚本添加不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29952207/

相关文章:

javascript - 使用 ajax 和 php 提交表单

mysql - 与独立的 mariaDB 服务器相比,galera 的性能非常差

c# - 为什么要在移动环境中使用 Entity Framework?

c# - 发布 IFormFile 时出现错误请求 (400)

php - Wordpress-按自定义字段获取帖子

php - 不接受数据库查询中的文本值,但只允许数字

php - 如何在 HEREDOC SQL 查询中使用 PHP 变量?

python - django 编码为 utf8 不工作

mysql - Magento 向左连接

c# - ModelState.IsValid 即使它不应该?