简体   繁体   English

如何将此 mysqli 转换为 PDO?

[英]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 .另请参阅此答案

  • Best Practise: Do not use SELECT * instead define each column you need to grab from the table.最佳实践:不要使用SELECT *而是定义您需要从表中获取的每一列。
  • Do not globalise your connection variable.不要全球化您的连接变量。 This is a security risk as well as adding bloat and should be unneeded on your code.这是一个安全风险以及增加膨胀,应该在您的代码中不需要。
  • Because it is a static statement you can use ->query rather than prepare , as nothing needs to be prepared.因为它是一个静态语句,您可以使用->query而不是prepare ,因为不需要prepare任何东西。

Solution:解决方案:

$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);
}

Alternatively:或者:

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";
}

See Also:也可以看看:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM