Skip to content
Advertisement

MYSQLi query not producing expected results

I am having a problem getting results I can use from my query. Code:

    //Create query
$stmt = $con->stmt_init();
$query = "SELECT * FROM `users` WHERE `userlogin` = '$username' AND `user_passwrd` = sha1(CONCAT('$userpw', `stamp`))"; 
$result = $con->query($query);
$rows = array();
if($stmt->prepare($query)) {
    if($stmt->execute()) {
        while($row = $result->fetch_array()) { 
            $rows[] = $row;
        }
    }
}
$result->free();
var_dump($row); //Returns NULL
die();
$num = mysqli_num_rows($result);
$ulogin = $row['userlogin'];
$pending = $row['pending'];
$acclvl = $row['user_accesslevel'];

I can get results with var_dump($rows) but I’m obviously doing something wrong here. I am unable to populate the variables and don’t know why. Any help would be appreciated. Cheers

Advertisement

Answer

You’re looping through the resulting rows until there are not more results and fetch_array() (and thereby $row) is NULL;

while($row = $result->fetch_array()) { 
    $rows[] = $row;
}

…so…

var_dump($row); //Returns NULL

…is hardly a surprise anymore 🙂

A simple way to do this would be something like this (can’t test run this, so see more as a hint, and you should really parameterise your query)

$query = "SELECT * FROM `users` WHERE `userlogin` = '$username' AND `user_passwrd` = sha1(CONCAT('$userpw', `stamp`))"; 
$result = $con->query($query);
if(!$result)
   die("horribly");
$row = $result->fetch_array()
$result->free();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement