2013-05-03 73 views
3

我以前做的:mysql_fetch_assoc()的PDO方法?

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

我读了MySQL的语句都已过时,不应该被使用。

我如何用PDO做到这一点?

第一行是:

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

怎么样的mysql_fetch_assoc()函数?

我使用PHP

+0

第一行是'$语句= $ DB->准备( “SELECT * FROM表WHERE ID =:ID”);'作为将用户数据在你的查询中使用字符串连接是**危险**。 – tadman 2013-05-03 16:43:07

+0

我知道,我做了一个编辑,以表明我只需要mysql_fetch_assoc()函数 – donparalias 2013-05-03 16:43:52

回答

5

您可以使用(PDO::FETCH_ASSOC)不断
使用将 while ($res = $stmt->fetch(PDO::FETCH_ASSOC)){ .... }
这里的参考(准确记录):http://www.php.net/manual/en/pdostatement.fetch.php

+0

现在我该如何引用“数字”列?加载'$ res'后的 – donparalias 2013-05-03 17:02:54

+1

,您可以简单地将它称为'mysql_fetch_assoc'。 '$ res ['number']'会做 – 2013-05-03 17:11:49

1

的手册中的所有井documentned:http://php.net/manual/en/pdostatement.fetchall.php

作为例子:

<?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); 
?> 
+4

+1,但我会说它的地图更接近['fetch'](http://php.net/manual/) en/pdostatement.fetch.php)比['fetchAll'](http://www.php.net/manual/en/pdostatement.fetchall.php)。 – 2013-05-03 16:43:38

+0

没错,但这只是一个例子,会将他引向手册(并在其中搜索)。我喜欢这样做,而不是在这样的情况下给出完整的答案。 – 2013-05-03 16:44:25

0

这是一个很好的教程: 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); 
?> 
+0

这是错误的吗?为什么它得到-1? – donparalias 2013-05-03 16:51:49

+0

这应该是正确的,尽管fetchAll并不像mysql_fetch_assoc()那样真正起作用,它会逐行返回。我正在使用它 – 2013-05-03 17:13:39

+0

@WillyPt我只是给出一个通用示例来向他展示语法,并且它已经在教程中提到过。查看教程中的“运行简单选择语句”。 – 2013-05-03 17:41:38

1

有一个很好的手动right here

从中您可以了解每次获取时不需要明确设置获取模式。
......甚至什么用PDO你并不需要在所有非数组呼应了许多:

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

那么,也有原来在http://php.net/pdostatement.fetch.php – feeela 2013-05-03 19:10:11

-2

您可以使用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 
} 

你可以找到一个很好的教程here

+0

这是既不好,也没有教程。而不是一个答案。 – 2013-05-09 05:52:33