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. :\
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().
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.
You can use fetchColumn()
:
$q= $conn->prepare("SELECT name FROM `login_users` WHERE username=?"); $q->execute([$userid]); $username = $q->fetchColumn();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With