mysql pdo 查询一条数据,使用mysql php 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.

COMMUNITY EDIT:

For security reasons, avoid concatenating strings to form an SQL query, use prepared statements instead.

Thus, instead of the vulnerable

$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

]);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值