Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return one value from database with mysql php pdo

Tags:

php

mysql

pdo

Im not trying to use a loop. I just one one value from one column from one row. I got what I want with the following code but there has to be an easier way using PDO.

try {         $conn = new PDO('mysql:host=localhost;dbname=advlou_test', 'advlou_wh', 'advlou_wh');         $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);     } catch(PDOException $e) {         echo 'ERROR: ' . $e->getMessage();     }  $userid = 1;  $username = $conn->query("SELECT name FROM `login_users` WHERE username='$userid'"); $username2 = $username->fetch(); $username3 = $username2['name'];  echo $username3; 

This just looks like too many lines to get one value from the database. :\

like image 427
Amber Stillwell Avatar asked Aug 13 '12 04:08

Amber Stillwell


People also ask

What PDO execute return?

PDO::exec() executes an SQL statement in a single function call, returning the number of rows affected by the statement. PDO::exec() does not return results from a SELECT statement. For a SELECT statement that you only need to issue once during your program, consider issuing PDO::query().

Is PDO better than MySQLi?

Both MySQLi and PDO have their advantages: PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases. So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries.


1 Answers

You can use fetchColumn():

$q= $conn->prepare("SELECT name FROM `login_users` WHERE username=?"); $q->execute([$userid]); $username = $q->fetchColumn(); 
like image 71
Ouadie Avatar answered Oct 14 '22 11:10

Ouadie