Simple way to read single record from MySQL

后端 未结 20 1358
一整个雨季
一整个雨季 2020-11-30 23:46

What\'s the best way with PHP to read a single record from a MySQL database? E.g.:

SELECT id FROM games

I was trying to find an answer in t

20条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 00:35

    Using PDO you could do something like this:

    $db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
    
    $stmt = $db->query('select id from games where ...');
    $id = $stmt->fetchColumn(0);
    if ($id !== false) {
        echo $id;
    }
    

    You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)

提交回复
热议问题