PHP:如何在不使用数组的情况下从MySQL中选择单个值。

时间:2022-09-25 16:21:12

I am new to PHP and have a really basic question.

我是PHP新手,有一个非常基本的问题。

If I know the result of a query is only a single value (cell) from a single row in MySQL how can I simplify the below without having to go through an array of results and without increasing the risk of SQL injection ?

如果我知道一个查询的结果只是一个单一的值(cell),那么在MySQL中,我如何能够简化下面的操作,而不必经过一系列的结果,而不增加SQL注入的风险?

In the example below I would just need to echo a single email as the result of the query.

在下面的示例中,我只需要回显查询结果中的单个电子邮件。

I found a couple of posts suggesting different approaches with fetch_field for this but I am not sure what is the best way here since some of these seem to be pretty old or deprecated now.

我发现了一些关于fetch_field的不同方法的文章,但是我不确定这里最好的方法是什么,因为其中有些似乎已经过时了,或者已经过时了。

My PHP:

我的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"];

Many thanks in advance.

提前感谢。

1 个解决方案

#1


4  

You can avoid caring what the column is called by just 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;

#1


4  

You can avoid caring what the column is called by just 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;