首页 > 解决方案 > 无法显示 SELECT 结果 sql

问题描述

我尝试获取 gmail = $gmail 的 id 并将其用于 UPDATE 表

但我不能从 id 使用并显示错误 Undefined property: mysqli_result::$fetch_assoc

功能 addverificationcode ($gmail , $random) {

    $connection = mysqli_connect(DataBaseManager::HOST, DataBaseManager::USER, DataBaseManager::PASSWORD, DataBaseManager::DATABASENAME);
    mysqli_set_charset($connection, "utf8");
    $sqlQuery = "SELECT id FROM users WHERE gmail='$gmail'";
    $result = mysqli_query($connection, $sqlQuery);
    if ($result->num_rows > 0) {
            $sqlCommand = "UPDATE users
                      SET verificationcode  = '$random' 
                        WHERE id = $result->fetch_assoc()";
    }

    if(mysqli_query($connection, $sqlCommand)){
        return true;
    }else{
        echo("Error description: " . mysqli_error($connection));
        return false;
    }


    }

标签: phpandroidmysqlsqlselect

解决方案


You have to use curly braces when calling a method in an object:

        $sqlCommand = "UPDATE users
                  SET verificationcode  = '$random' 
                    WHERE id = {$result->fetch_assoc()}";

An alternative is using concatenation:

        $sqlCommand = "UPDATE users
                  SET verificationcode  = '$random' 
                    WHERE id = " . $result->fetch_assoc();

Note that in this case you could combine the two SQL statements into just one, for example update .. where id = (select id from ...).

Also note that your code as posted is vulnerable to an SQL injection attack. See How can I prevent SQL injection in PHP?


推荐阅读