从数据库返回一个值

从数据库返回一个值

本文介绍了使用 mysql php 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

这篇关于使用 mysql php pdo 从数据库返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 07:02