gpt4 book ai didi

php - PDO 中的 mysql_result

转载 作者:行者123 更新时间:2023-11-29 06:44:20 24 4
gpt4 key购买 nike

下面是我的代码,都是用mysql写的。我正在尝试切换到 PDO。我的问题是,PDO 中的 mysql_result 相当于什么?

$query = "SELECT id, firstname, lastname FROM table";
if($mysql_query = mysql_query($query)){
$id = mysql_result($mysql_query, 0, 'id');
$firstname = mysql_result($mysql_query, 0, 'firstname');
$lastname = mysql_result($mysql_query, 0, 'lastname');
}

到目前为止,我只能通过执行以下操作来执行 $query。

$query = $PDO -> prepare("SELECT id, firstname, lastname FROM table");
$query -> execute();

最佳答案

正如 Ian 上面所说的一种方式,或者如果您不使用准备功能,那么您可以这样做:

$sth = $PDO->query("SELECT id, firstname, lastname FROM table");

if ($sth->rowCount() > 1) {
// One way to get the results if you have more then one row
foreach ($sth as $row) {
echo "ID: ".$row['id']."\n";
echo "First name: ".$row['firstname']."\n";
echo "Last name: ".$row['lastname']."\n";
}
} elseif ($sth->rowCount() == 1) {
// Or this way if you just have one row
$result = $sth->fetch(PDO::FETCH_ASSOC);

echo "ID: ".$result['id']."\n";
echo "First name: ".$result['firstname']."\n";
echo "Last name: ".$result['lastname']."\n";
}

关于php - PDO 中的 mysql_result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19601814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com