PHP: how to select one value from one row in MySQL without using an array for results
I am new to PHP and have a really basic question.
If I know that the query result is only one value (cell) from one row in MySQL , how can I simplify the following without having to loop through the result array and without increasing the risk of SQL injection?
In the example below, I would just need to drop one email as a result of the request.
I found a couple of posts suggesting different approaches since fetch_field
for this, but I'm not sure if here's the best way as some of them seem to be quite old or outdated.
My PHP:
$stmt = $conn->prepare("SELECT email FROM Users WHERE userName = ? LIMIT 1");
$stmt->bind_param('s', $userName);
$stmt->execute();
$result = $stmt->get_result();
$arr = $result->fetch_assoc();
echo $arr["email"];
Thank you very much in advance.
+3
source to share
1 answer
You can avoid worrying about what is being called from the column by simply doing this:
<?php
$stmt = $conn->prepare("SELECT email FROM Users WHERE userName = ? LIMIT 1");
$stmt->bind_param('s', $userName);
$stmt->execute();
$email = $stmt->get_result()->fetch_object()->email;
echo $email;
+4
source to share