简体   繁体   English

mysql_fetch_assoc()的PDO方法?

[英]PDO method for mysql_fetch_assoc()?

I used to do : 我曾经做过 :

$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];

I read that mysql statements are all deprecated and should not be used. 我读过mysql语句都已弃用,不应该使用。

How can i do this with PDO? 我怎么能用PDO做到这一点?

The first line would be : 第一行是:

$stmt = $db->prepare("SELECT * FROM table WHERE id = " . $id); // there was an aditional double quote in here.
$stmt->execute(array(':id' => $id));

What about the mysql_fetch_assoc() function? mysql_fetch_assoc()函数怎么样?

I am using php 我正在使用PHP

You can use (PDO::FETCH_ASSOC) constant 您可以使用(PDO::FETCH_ASSOC)常量
Usage will be while ($res = $stmt->fetch(PDO::FETCH_ASSOC)){ .... } 用法将是while ($res = $stmt->fetch(PDO::FETCH_ASSOC)){ .... }
Here's the reference (documentation precisely) : http://www.php.net/manual/en/pdostatement.fetch.php 以下是参考文献(文档准确): http//www.php.net/manual/en/pdostatement.fetch.php

All well documentned in the manual: http://php.net/manual/en/pdostatement.fetchall.php 所有文档都在手册中记录: http//php.net/manual/en/pdostatement.fetchall.php

As example: 例如:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>

There is a nice manual right here . 有一个很好的手册就在这里

From which you can learn what you don't need to set fetch mode explicitly with every fetch. 您可以从中了解每次获取时不需要显式设置获取模式的内容。
...and even what with PDO you don't need no arrays at all to echo a number: ...甚至PDO你根本不需要任何数组来回应一个数字:

$stmt = $db->prepare("SELECT number FROM table WHERE id = ?");
$stmt->execute(array($id));
echo "Hello User, your number is".$stmt->fetchColumn();

This is a nice tutorial: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers 这是一个很好的教程: http//wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

<?php
   $db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
   $stmt = $db->query("SELECT * FROM table");
   $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
   var_dump($results);
?>

You can use PDO::FETCH_ASSOC for the same. 您可以使用PDO :: FETCH_ASSOC。

$stmt = $db->prepare("SELECT * FROM table WHERE id = :id");
$stmt->execute(array(':id' => $id));
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
while($record = $stmt->fetch()) {
   //do something
}

You can find a good tutorial here 你可以在这里找到一个很好的教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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