0

感谢您是否可以帮助我将下面的 mysql 代码写入 PDO 语句。

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

     $result = mysql_query($sql);

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

      <?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)”的功能是什么

4

3 回答 3

0

如果您以前使用过 MySQL,我认为 sqlite DSN 不适合您。SQLite 是不同品牌的 RDBMS,它与 MySQL 不兼容。

要使用 PDO 连接到 MySQL,请参阅此手册页:http ://www.php.net/manual/en/ref.pdo-mysql.connection.php

例子:

<?php
$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'username';
$password = 'password';

$dbh = new PDO($dsn, $username, $password);
于 2013-07-10T02:09:24.460 回答
0

那行指向你的 sql 文件,它没有函数。它打开一个 PDO 连接,您可以进一步查询。

$connection = new pdo("sqlite:/path/to/sql/file.sq3");

PDO::FETCH_ASSOC告诉函数fetch()从表中提取关联数组。

于 2013-07-10T01:50:42.237 回答
0

you connect to the database like this :

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

and next we query like this :

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

and we fetch it like this :

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

and now you use $row->name for example

here is more about 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

于 2013-07-10T01:53:21.073 回答