php - 如何将mysql查询写入PDO

标签 php mysql pdo

如果您能帮我将下面的 mysql 代码写入 PDO 语句,我将不胜感激。

     $sql  = "SELECT * FROM node WHERE node_name='$nodename'";

     $result = mysql_query($sql);

当我阅读 PDO::query 手册时,我发现了这段代码

      <?php
      $connection = new pdo("sqlite:file.sq3");
      $query="SELECT * FROM table";
      $result = $connection->query($query);
      $row = $result->fetch(PDO::FETCH_ASSOC);
      print_r($row);
      ?>

“sqlite:file.sq3”和“(PDO::FETCH_ASSOC)”的函数是什么

最佳答案

您像这样连接到数据库:

try {
$db = new PDO("sqlite:file.sq3");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
       echo 'Error : <br>' . $e->getMessage();
}

PS: You dont need the try and the catch, but we used to get the error and handle it in a nice way as we want to

接下来我们像这样查询:

 $db->query(SELECT * FROM node WHERE node_name='$nodename'");

我们像这样获取它:

 $query = $db->query(SELECT * FROM node WHERE node_name='$nodename'");
 $row   = $query->fetch(PDO::FETCH_OBJ);

现在您使用 $row->name 例如

这里有更多关于 PDO::FETCH 的内容

  • PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set

  • PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

  • PDO::FETCH_BOUND: returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were
    bound with the PDOStatement::bindColumn() method

  • PDO::FETCH_CLASS: returns a new instance of the requested class, mapping the columns of the result set to named properties in the
    class. If fetch_style includes PDO::FETCH_CLASSTYPE (e.g.
    PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE) then the name of the class
    is determined from a value of the first column.

  • PDO::FETCH_INTO: updates an existing instance of the requested class, mapping the columns of the result set to named properties in
    the class

  • PDO::FETCH_LAZY: combines PDO::FETCH_BOTH and PDO::FETCH_OBJ, creating the object variable names as they are accessed

  • PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0

  • PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set

关于php - 如何将mysql查询写入PDO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17561175/

相关文章:

php - 我想从我的网站简单地重定向到某个网址,而无需刷新 session

mysql - 向其他用户授予执行功能权限

php - 使用 pdo 插入 cookie 值

mysql - 重新计数以修复 mysql 中的主 id

php - 如何使用PDO锁定sqlite数据库中的条目?

php - PDO select语句卡在询问数据库的部分

php - 如何在 Laravel join 中使用 'DATEADD' 函数?

php - 将 32 位 TGA 转换为 PNG

php - 使用 PHP linux 将 doc、docx、pdf 转换为 HTML

php - PHP 准备语句中的问号不起作用?