Check for presence of phpsql data (using PDO)

Asked 2 years ago, Updated 2 years ago, 36 views

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?

php mysql

2022-09-22 18:41

1 Answers

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';

However, Usually does this to prevent injection attacks through variable binding and to increase the efficiency of viewing actual data.

// 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'];
}


2022-09-22 18:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.