简体   繁体   中英

PHP MySQL SELECT Statement with bindparam doesn't work

This is my code:

function getUsers($connection ,$username) {
    $sql = "SELECT * FROM users where username = ?";
    $stmt = $connection->prepare($sql);
    $stmt->bindParam("s", $username, PDO::PARAM_STR);
    return  $stmt->fetchAll();  
}

$voornaam = "dave";
$users = getUsers($connection, $voornaam);
print_r($users);

When I open my webpage, I get an empty Array.
I checked, and there is a user with the username "dave" in my database. This should work, however, it doesn't...
Anyone knows what I did wrong?

Thanks in advance.

First is, you have to execute it before using fetchAll():

$stmt->execute();
$result = $stmt->fetchAll();

This is the correct way:

$stmt = $connection->prepare('SELECT * FROM users where username = :username');
$stmt->bindParam(':username', $username); 

If you want to user? it will determine the order of? in bindParam, use it like this:

$sql = "SELECT * FROM users where username = ?";
$stmt = $connection->prepare($sql);
$stmt->bindParam(1, $username, PDO::PARAM_STR);

More example:

$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);

Instead of using

$stmt->bindParam("s", $username, PDO::PARAM_STR);

you need to use

$stmt->bindParam(1, $username, PDO::PARAM_STR);

Check this link for details https://www.php.net/manual/en/pdostatement.bindparam

You need to check this Example #2 Execute a prepared statement with question mark placeholders This is the correct way

$sql = "SELECT * FROM users where username = ?";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $username, PDO::PARAM_STR);
$stmt->execute();
return  $stmt->fetchAll(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM