mysqli/mysql query inside function not working

后端 未结 2 1750
迷失自我
迷失自我 2020-12-15 09:36

I\'m tryin to build some functions for a website of mine and some of them consist in fetching data from the mysql database. When I test the code outside of the function it s

相关标签:
2条回答
  • 2020-12-15 10:11

    You probably need to use the global keyword, otherwise $db is considered a var in local scope.

    function sanitize ($data){
        global $db;
        $db->mysqli_real_escape_string($data);
    }
    
    function user_exists($usermail){
        global $db;
        $usermail = sanitize($usermail);
        $query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
        $check = $query->num_rows;
        return ($check == 1) ? true : false;
    }
    
    0 讨论(0)
  • 2020-12-15 10:17

    Try to connect inside the function, and connection needs to be included before you include functions.

    Something like this:

    function user_exists($usermail){
        $db = new MySQLi("localhost","test","test","test");
        $usermail = sanitize($usermail);
        $query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
        $check = $query->num_rows;
        return ($check == 1) ? true : false;
    }
    
    0 讨论(0)
提交回复
热议问题