PDO get data from database

前端 未结 3 1632
名媛妹妹
名媛妹妹 2020-12-03 17:52

I started using PDO recently, earlier I was using just MySQL. Now I am trying to get all data from database.

$getUsers = $DBH->prepare(\"SELECT * FROM use         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 18:54

    Your code is missing a call to execute() after prepare(). After your prepared statement is executed you can get the array of records using fetchAll().

    $getUsers = $DBH->prepare('SELECT * FROM users ORDER BY id ASC');
    $getUsers->execute();
    $users = $getUsers->fetchAll();
    
    // Then in your presentation logic you can use the following code to display the data:
    if ($users) {
        foreach ($users as $user) {
            echo $user['username']."
    "; } } else { // Whatever your requirement is to handle the no user case, do it here. echo 'Error: No users.'; }

    However, in you example you are not passing any variable data to the query and you only execute it once, which defeats a purpose of having prepared statement. You should use prepared statements if you need to have variables in your SQL, for example:

    $getUsers = $DBH->prepare('SELECT * FROM users WHERE id=?');
    $getUsers->execute([
        $_GET['user_id']
    ]);
    $user = $getUsers->fetch();     // get single user by unique id
    

    If there are no variables then you can simply use query() method.

    $users = $DBH->query('SELECT * FROM users ORDER BY id ASC')->fetchAll();
    

    If you do not need to fetch all records at once, you can simply loop on the statement with foreach:

    $getUsers = $DBH->prepare('SELECT * FROM users WHERE username LIKE ? ORDER BY id ASC');
    $getUsers->execute([
        '%' . $_GET['search'] . '%'     // search for username with wildcards
    ]);
    
    foreach ($getUsers as $user) {
        echo $user['username']."
    "; }

提交回复
热议问题