我可以用什么代替mysql_fetch_array?

时间:2012-02-23 09:51:06

标签: php

在我的php代码中,我从数据库中获取数据,并将数据放入特定值:

$from_db=mysql_query(" SELECT * FROM ... ");

while ($row = mysql_fetch_array($from_db)) {
$number_id[]=$row['number_id'];
...
}

现在我想在命令“while”之前添加这一行(用于其他目的):

$from_db = mysql_fetch_array($from_db);

如何更改此行:while ($row = mysql_fetch_array($from_db)) {来处理数组而不是数据库中的原始数据?

4 个答案:

答案 0 :(得分:4)

我建议您改用PDO class。不建议使用mysql_ *函数,并且将在(远)将来弃用。

一个例子是:

//Connect to database and whatnot
//...
$PDOquery=$PDO->prepare('SELECT * FROM users WHERE id=?;');
$PDOquery->execute(array(1));
$resultArray=$PDOquery->fetchAll(PDO::FETCH_ASSOC); //Results stored as associative array in ths array.

答案 1 :(得分:0)

不幸的是,有必要这样做:

$from_db=mysql_query(" SELECT * FROM ... ");

$from_db = array();

while ($row = mysql_fetch_array($from_db)) {
  $from_db[] = $row;
}

foreach($from_db as $row) {
  $number_id[]=$row['number_id'];
}

答案 2 :(得分:0)

您最好使用PDOMySQLi

例如,PDOStatement::fetchAll

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

答案 3 :(得分:-1)

mysql_fetch_assoc()
mysql_fetch_object() 

http://php.net/manual/en/function.mysql-fetch-assoc.php