【问题标题】:MySqli statement execute returns false even if data gets inserted即使插入了数据,MySqli 语句也执行返回 false
【发布时间】:2015-02-19 06:36:33
【问题描述】:

这是我的简单纤薄应用程序。下面的这个函数处理插入。

public function createSelfie($user_id, $image, $latitude, $longitude) {
        $stmt = $this->conn->prepare("INSERT INTO user_selfie(image, latitude, longitude, user_id) VALUES(?,?,?,?)");
        $stmt->bind_param("sssi", $image, $latitude, $longitude, $user_id);
        $result = $stmt->execute();
        $stmt->close();

        if ($result) {
            // we were successful in storing the selfie now we need to manipulate the 'user_egg' table values
            return SELFIE_CREATED_SUCCESSFULLY;
        }

        else {
            // selfie failed to create
            return NULL;
        }

    }

为此,路线如下:

$app->post('/selfie/create', function() use ($app) {
            verifyRequiredParams(array('image', 'latitude', 'longitude', 'user_id'));

            // reading post params
            $image = $app->request()->post('image');
            $latitude = $app->request()->post('latitude');
            $longitude = $app->request()->post('longitude');
            $user_id = $app->request()->post('user_id');
            $response = array();

             $db = new DbHandler();
             $res = $db->createSelfie($user_id, $image, $latitude, $longitude);

             if ($res == SELFIE_CREATED_SUCCESSFULLY) {
                $response['error'] = false;
                $response["message"] = "Your selfie created successfully";
                echoRespnse(201, $response);
             }

             else {
                $response['error'] = true;
                $response["message"] = "There was an error storing your selfie try again";
                echoRespnse(200, $response);
             }

        });

现在有时它会正确响应,有时会为空。但是每次该语句确实被执行时,我都会看到插入的行。然后我很困惑为什么函数返回false。可能是什么原因?如果我们无法知道原因,使用 afftected_rows 而不是结果是一种好习惯吗?附带说明一下,我确实有一个 echoRespnse 方法,它 json 编码结果并将响应作为 json 发送。

【问题讨论】:

    标签: php mysqli slim


    【解决方案1】:

    而不是“返回 SELFIE_CREATED_SUCCESSFULLY;” 试试

    return true;
    

    【讨论】:

    • 您好,感谢您的快速回复。但是,为什么您认为这会解决问题。不管怎样,我要试试看。
    • 我假设 SELFIE_CREATED_SUCCESSFULLY 是一个没有数据且等于 NULL 或 0 的变量,这将使其返回 FALSE。如果语句正确运行,您使用该函数返回 TRUE 或非 FALSE。您返回 FALSE 但不返回 TRUE。
    • 在我的 config.php 中,我已将其声明为常量。 define('SELFIE_CREATED_SUCCESSFULLY', 3); 所以即使在这之后,这点有意义吗?我认为除了 0 以外的任何东西都是正确的
    • 顺便说一句,同样的问题仍然存在。
    • 嗯,除 0 以外的任何值都应该被视为 TRUE,所以我猜这不是问题。它总是返回假吗?我会回显 $result 以查看它在代码的每个部分中的实际价值。在 IF 语句之前、之后和中。可能会澄清发生了什么。还有一件事是 $result 可能会在 CLOSE 后丢失它的数据。祝你好运。
    猜你喜欢
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多