使用 mysql php pdo 从数据库返回一个值

2021-12-26 00:00:00 php mysql pdo

我不想使用循环.我只是来自一行的一列的一个值.我用以下代码得到了我想要的东西,但必须有一种更简单的方法来使用 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. :

推荐答案

您可以为此创建一个函数,并在每次需要单个值时调用该函数.出于安全原因,请避免连接字符串以形成 SQL 查询.相反,对值使用准备好的语句并对 SQL 字符串中的其他所有内容进行硬编码.为了获得某个列,只需在您的查询中明确列出它.fetchColumn() 方法也可以方便地从查询中获取单个值

You could create a function for this and call that function each time you need a single value. For security reasons, avoid concatenating strings to form an SQL query. Instead, use prepared statements for the values and hardcode everything else in the SQL string. In order to get a certain column, just explicitly list it in your query. a fetchColumn() method also comes in handy for fetching a single value from the query

function getSingleValue($conn, $sql, $parameters)
{
    $q = $conn->prepare($sql);
    $q->execute($parameters);
    return $q->fetchColumn();
}

然后你可以简单地做:

$name = getSingleValue($conn, "SELECT name FROM login_users WHERE id=?", [$userid]); 

它会给你想要的价值.

因此您只需创建该函数一次,但可以将其重用于不同的查询.

So you need to create that function just once, but can reuse it for different queries.

此答案已由社区编辑以解决安全问题

This answer has been community edited addressing security concerns

相关文章