gpt4 book ai didi

php - 如何将mysql查询写入PDO

转载 作者:行者123 更新时间:2023-11-30 01:30:17 25 4
gpt4 key购买 nike

如果您能帮我将下面的 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/

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