Search code examples
phpprepared-statementmysqli

Unable to fetch multiple row data from mysql using prepared object statements


$sql = $conn->prepare("SELECT username, email FROM users WHERE username=? OR email = ?");
$sql->bind_param('ss', $uname, $email);
$sql->execute();
$result = $sql->get_result();
$row = $result->fetch_array(MYSQLI_ASSOC);

if ($row['username'] == $uname) {
    echo "Username not availabe try different";
} elseif ($row['email'] == $email) {
    echo "email is already taken diiferent";
} else {
    $stmt = $conn->prepare("INSERT INTO users (username, email, pass, created) VALUES (?, ?, ?, ?)");
    $stmt->bind_param('ssss', $username, $email, $pass, $created);
    if ($stmt->execute()) {
        echo "Registrated sucessfully. Login Now!";
    } else {
        echo "Something went wrong. Please try again";
    }
}

This code is not running. I don't know why. If I'm fetching a single row then it is working but for multiple rows it is not working.

Here I want to validate whether a username and email already exists in the db using prepared statements.


Solution

  • Finally, after a 3-4 hours of exercise, I resolve this issue with help of this stack overflow article:call-to-undefined-method-mysqli-stmtget-result

    If anyone have same issue because of native driver refer to this article. This is the solution which works for me is given below: First define this function

    function fetchAssocStatement($stmt)
    {
        if($stmt->num_rows>0)
        {
            $result = array();
            $md = $stmt->result_metadata();
            $params = array();
            while($field = $md->fetch_field()) {
                $params[] = &$result[$field->name];
            }
            call_user_func_array(array($stmt, 'bind_result'), $params);
            if($stmt->fetch())
                return $result;
        }
    
        return null;
    }
    

    as you can see it creates an array and fetches it with the row data, since it uses $stmt->fetch() internally, you can call it just as you would call mysqli_result::fetch_assoc (just be sure that the $stmt object is open and result is stored). Now call the above function:-

    //mysqliConnection is your mysqli connection object
    if($stmt = $mysqli_connection->prepare($query))
    {
        $stmt->execute();
        $stmt->store_result();
    
        while($assoc_array = fetchAssocStatement($stmt))
        {
            //do your magic
        }
    
        $stmt->close();
    }