[英]How can I convert this mysqli to PDO?
<?php
require_once('dbconfig.php');
global $con;
$query = $con->prepare("SELECT * FROM userinfo order by id DESC");
$query->execute();
mysqli_stmt_bind_result($query, $id, $name, $username, $password);
Try this尝试这个
$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
PDO::ATTR_EMULATE_PREPARES => false, // turn off emulation mode for "real" prepared statements
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
$pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
error_log($e->getMessage());
exit('Something weird happened'); //something a user can understand
}
$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);
You should use ->bindColumn
Manual你应该使用
->bindColumn
手册
See also This answer .另请参阅此答案。
SELECT *
instead define each column you need to grab from the table.SELECT *
而是定义您需要从表中获取的每一列。->query
rather than prepare
, as nothing needs to be prepared.->query
而不是prepare
,因为不需要prepare
任何东西。$query = $con->query("SELECT id,name,username,password FROM userinfo ORDER BY id DESC");
try {
$query->execute();
$query->bindColumn(1, $id);
$query->bindColumn(2, $name);
$query->bindColumn(3, $username);
$query->bindColumn(4, $password);
}
catch (PDOException $ex) {
error_log(print_r($ex,true);
}
A nice feature of PDO::query() is that it enables you to iterate over the rowset returned by a successfully executed SELECT statement.
PDO::query() 的一个很好的特性是它使您能够迭代成功执行的 SELECT 语句返回的行集。 From the manual
从手册
foreach ($conn->query('SELECT id,name,username,password FROM userinfo ORDER BY id DESC') as $row) {
print $row['id'] . " is the ID\n";
print $row['name'] . " is the Name\n";
print $row['username'] . " is the Username\n";
}
Mzea Has some good hints on their answer, you should use their $options
settings as well as using their suggested utf8mb4
connection character set. Mzea对他们的回答有一些很好的提示,您应该使用他们的
$options
设置以及他们建议的utf8mb4
连接字符集。
And their suggestion for using ->fetchAll
is also completely valid too.他们对使用
->fetchAll
的建议也完全有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.