为什么mysqli和PDO会给我不同的结果

时间:2014-05-02 13:48:04

标签: php mysql pdo mysqli

这是我正在使用的代码片段 -

    //mysqli
    $db_conn = mysqli_connect('localhost', 'root', 'XXXX', 'core');        
    $db = mysqli_select_db($db_conn, 'core');
    $result = mysqli_query($db_conn, 'SELECT * FROM customers WHERE email = "juz_acool1@gmail.com"');
    $result_rows= mysqli_fetch_assoc($result);
    var_dump($result_rows);

    //pdo
    $dsn = "mysql:host=localhost;dbname=core;";
    $u = 'root';
    $p = 'XXXX';
    $pdo = new PDO($dsn, $u, $p);
    var_dump($pdo);
    $test = $pdo->exec('show databases;');
    var_dump($test);
    var_dump($pdo);

    $query = $pdo->prepare("SELECT * FROM customers WHERE email = 'juz_acool1@gmail.com'");
    var_dump($query);        
    $r = $query->execute();
    var_dump($r);

这就是我得到的结果 -

  //mysqli 
  array (size=10)
  'id' => string '1' (length=1)
  'fullname' => string 'Shalom Sam' (length=10)
  'username' => string 'shalom.sam' (length=10)
  'email' => string 'juz_acool1@gmail.com' (length=19)
  'birthdate' => string '05/25/1986' (length=10)
  'gender' => string 'm' (length=1)
  'location' => string 'Mumbai, Maharashtra, India' (length=26)
  'verified' => string '1' (length=1)
  'timezone' => string '5.5' (length=3)
  'lastupdatetime' => string '2014-05-02 15:42:35' (length=19)

//pdo
int 0

object(PDO)[4]

object(PDOStatement)[5]

  public 'queryString' => string 'SELECT * FROM customers WHERE email = 'juz.cool1@gmail.com'' (length=59)

boolean false

我知道这一切需要阅读很多。但我真的想知道我可能会出错的地方。希望有人可以帮助我。

2 个答案:

答案 0 :(得分:1)

在您的PDO结果上使用提取

$r = $query->execute();
$res = $r->fetch(PDO::FECTH_ASSOC);
var_dump($res);

在这里,请阅读,它应该回答所有这些类型的问题

http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

答案 1 :(得分:-1)

看起来您错过了一个步骤,您需要定义PDO在尝试显示数据之前如何获取数据。

试试这个

$host = 'localhost';
  $dbname = 'database name';
  $user = 'user name';
  $pass = 'password';

$DB = new pdo("mysql:host=$host;dbname=$dbname", $user, $pass);

$STH = $DB->query('SELECT * FROM some_table');

# setting the fetch mode  
$STH->setFetchMode(PDO::FETCH_ASSOC); 

# fetching
while($row = $STH->fetch()) { 
    print('assoc'); 
    echo $row['ID'] . "\n";  
    echo $row['Book'] . "\n";  
    echo $row['colour'] . "\n";  
    print('<p>');
}