douhan4812 2017-02-14 02:10
浏览 78
已采纳

获取错误:类mysqli的对象无法在第5行转换为字符串[重复]

This question is an exact duplicate of:

I'm getting this error:

Catchable fatal error: Object of class mysqli could not be converted to string in C:\xampp\htdocs\gym\userAvailability.php on line 5

And this is the code:

<?php

function username_exists($username, $con){

    $sql = "SELECT * FROM admin WHERE username = '$username'";
    $result = mysqli_query($con, sql);
    $resultarr = mysqli_fetch_assoc($result);


    if(!mysqli_num_rows($result) == 1){
        return true;
    }else{
        return false;
    }
}

I've also checked all the variable name from the .php file that the function username_exist is being used and it is all correct. Any ideas on how to fix this?

</div>
  • 写回答

1条回答 默认 最新

  • doujia1904 2017-02-14 02:32
    关注

    For one, this code is vulnerable to SQL injection - you should use prepared statements with placeholders instead. You're also fetching the result, which isn't used - so you can get rid of the mysqli_fetch_assoc() inside this function.

    Your actual issue though, is a dollar-sign missing in front of your $sql and the logic here if(!mysqli_num_rows($result) == 1) { is inverse. If there is a result, you basically get !1 == 1, which is false (as !1 becomes 0, so you get 0 == 1). So the inverse-operator ! had the result be the other way around.

    Cleaned a bit, fixed the logical issue and added prepared statements, would look like this

    function username_exists($username, $con){
        $stmt = $con->prepare("SELECT * FROM admin WHERE username = ?");
        $stmt->bind_param('s', $username);
        $stmt->execute();
        $stmt->store_result();
        $num_rows = $stmt->num_rows;
        $stmt->close();
    
        return $num_rows == 1 ? true : false;
    }
    

    This function would now return true if the username is found in the database. You should now use this function like

    if (!username_exists($_POST['username'], $con) {
        /* Do the insert to the database here */
    } else {
        /* The username was taken!
           Don't perform the INSERT query */
    }
    

    When passing the $username parameter to the function, use the raw username (don't use mysqli_real_escape_string() on it here, since we're using prepared statements).


    You might also want to look into adding the UNIQUE constraint for your username-column in the database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来