Getting results of statement

2019-09-07 06:26发布

问题:

I have made this example code:

$db = new mysqli("localhost","root","password","xxx");

$statement = $db->prepare("SELECT name, password FROM persons WHERE name=? LIMIT 1");

$statement->bind_param('s', "kevin");

$statement->execute();

if($statement->num_rows){

$statement->bind_result($dbname, $dbpassword);

$statement->free_result();

};

echo $dbname;
echo $dbpass;

How can use/get $dbname and $dbpassword directly without using something like:

while($statement->fetch()){
    echo $dbname;
}

I want to use $dbname and dbpassword directly. What is the best approach? What am I doing wrong.

回答1:

I found the answer:

I needed to store the result (Store the result (to get properties))

I needed to fetch the result (Fetch results from a prepared statement into the bound variables) Gladfully without a while loop.

$db = new mysqli("localhost","root","password","xxx");

$statement = $db->prepare("SELECT name, password FROM persons WHERE name=? LIMIT 1");

$statement->bind_param('s', "kevin");

$statement->execute();

$statement->store_result(); // this is what I was missing

if($statement->num_rows){

    $statement->bind_result($dbname, $dbpassword);

    $statement->fetch(); // this is what I was missing

    $statement->free_result();

    echo $dbname;

    echo $dbpass;

};


标签: php mysql mysqli