使用mysql php pdo从数据库返回一个值 [英] return one value from database with 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. :\
推荐答案
您可以为此创建一个函数,并在每次需要单个值时调用该函数
You could create a function for this and call that function each time you need a single value
function getSingleValue($tableName, $prop, $value, $columnName)
{
$q = $conn->query("SELECT `$columnName` FROM `$tableName` WHERE $prop='".$value."'");
$f = $q->fetch();
$result = $f[$columnName];
return $result;
}
然后您可以简单地进行以下操作:
Then you can simply do:
$singleValue = getSingleValue('login_users', 'username', $userid, 'name'); // will get you the value
因此,您只需创建一次该函数,即可将其重新用于具有不同列名的不同表.
So you need to create that function just once, but can reuse it for different tables with different column names.
社区 出于安全原因,请避免将字符串连接起来以形成SQL查询,而应使用准备好的语句.
COMMUNITY For security reasons, avoid concatenating strings to form an SQL query, use prepared statements instead.
因此,而不是脆弱的人
$q = $conn->query("SELECT `$columnName` FROM `$tableName` WHERE $prop='".$value."'");
在准备好的语句中使用相应的代码
Use the corresponding code with prepared statements
$q = $conn->prepare('SELECT :columnName FROM :tableName WHERE :property=:value', [
'columName' => $columnName,
'tableName' => $tableName,
'property' => $prop,
'value' => $value
]);
这篇关于使用mysql php pdo从数据库返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!