Hello, I'm a Php beginner.
Using PHP Data Object, if there is a user with a specific name in the user table, I want to print out that the user is present or not, so I want to print out a message that there is no user
$po = new PDO ("mysql:host=localhost:3306;dbname=userdb;charset=utf8;", "(account name)";
/*
···ㆍㆍㆍ
*/
$sql = "SELECT * FROM user WHERE name = 'Nickname'";
$result = $pdo->query($sql);
if (empty($result)) {
echo "Yes";
} } else {
echo "None";
}
/*
···ㆍㆍㆍ
*/
When I wrote it like this, I got an error message that doesn't say "None" because there is no user with nickname
. Is there any other way than using the empty function?
PDO::query()
itself can be used as like this.
$sql = "SELECT * FROM user WHERE name = 'Nickname'";
$result = $pdo->query($sql); //query() method returns data on failure, FALSE on success
echo $result === FALSE? 'None' : 'None';
// prepared query statements without user input being forced
$query = $pdo->prepare('SELECT id, created_at FROM user WHERE name = :username');
// Securely associate and execute values to prepared query statements
$query->execute ([':username' => 'nickname']);
// Take out and use one by one without recalling all the results of the executed query
while ($row = $query->fetch()) {
echo $row['id']. User subscription date: '.$row['created_at'];
}
© 2024 OneMinuteCode. All rights reserved.