2010-05-16 59 views
2

我只是想知道我怎么会能够代码执行一个SQL查询,然后每一行放入一个新的阵列,例如,让我们说某个表中查找类似如下:使用PHP将数据库行放入数组中?

$people= mysql_query("SELECT * FROM friends")  

输出:

| ID | Name | Age | 
--1----tom----32 
--2----dan----22 
--3----pat----52 
--4----nik----32 
--5----dre----65 

我如何创建一个多维数组,可以使用$ people [0] [1]和第五行第三列访问第一行第二列数据,使用$ people [4 ] [2]。

我将如何去构建这种类型的数组?

对不起,如果这是一个奇怪的问题,它只是我是PHP + SQL的新手,并想知道如何直接访问数据。性能和速度不是问题,因为我只是编写小测试脚本来掌握语言。

回答

7
$rows = array(); 
while ($row = mysql_fetch_array($result, MYSQL_NUM)) { 
    $rows[] = $row; 
} 
0
$array = array(); 
$sql = "SELECT * FROM friends"; 
$res = mysql_query($sql) or trigger_error(mysql_error().$sql); 
while($row = mysql_fetch_assoc($res)) $array[]=$row; 
+0

您应该初始化数组,否则如果没有行,则该变量未定义。 – Artefacto 2010-05-16 17:48:34

+0

好点的感谢 – 2010-05-16 17:50:09

1

您开放使用DB模块,像PEAR::DB模块?如果是这样,请查看this article by Paul Dubois关于使用PHP的Pear DB模块编写脚本。该模块已被superseded,但它会告诉你一些更先进(和更常见的)数据库实践的基础知识。

至于你的实际问题,你可以遍历所有行和填充数组...

$dsn = "mysqli://testuser:[email protected]/test"; 
$conn =& DB::connect ($dsn); 
if (DB::isError ($conn)) { /* ... */ } 

$result =& $conn->query ("SELECT * FROM friends"); 
if (DB::isError ($result)){ /* ... */ } 

while ($row =& $result->fetchRow()) { 
    $people[] = $row; 
} 
$result->free(); 

或者你可以写一个实现了ArrayAccess interface对象,请求特定的行,当你参考该指数。 (这个代码可能是完全错误的,但这里是我的尝试)

class FriendsTable implements ArrayAccess { 
    function offsetGet($key) { 
     $result =& $conn->query ("SELECT * FROM friends LIMIT $key, 1",); // careful; this is vulnerable to injection... 
     if (DB::isError ($result)){ die ("SELECT failed: " . $result->getMessage() . "\n"); } 
     $people = null; 
     if ($row =& $result->fetchRow()) { 
      $people = $row; 
     } 
     $result->free(); 
     return $people; 
    } 

    function offsetSet($key, $value) { 
     /*...*/ 
    } 

    function offsetUnset($key) { 
     /*...*/ 
    } 

    function offsetExists($offset) { 
     /*...*/ 
    } 
} 

$people = new FriendsTable(); 
$person = $people[2]; // will theoretically return row #2, as an array 

...什么的。

+1

我觉得很有意思,在你执行你用毫无理由引用offsetget,然后根据你应该(至少如果你想要的东西像一个$ =新FriendsTable不要返回引用() ; $ a [“foo”] [“bar”] = 42;工作)。但否则,+1。 – Artefacto 2010-05-16 18:07:14

+0

雅,我复制粘贴有点仓促了我挂的文章,我认为它的意思更多PHP4 ...你建议我删除了引用,或者我应该添加引用回报? – 2010-05-16 18:10:45

+1

真的没有理由通过引用$ result和$ people来分配。如参考返回,这是offsetget的通常的行为,所以像$一个[ “foo” 的] [ “酒吧”] = 42的东西,$ A [ “foo” 的] - >巴= 42或取消($ A [ “foo”] [“bar”])有任何作用。为了公平起见,在这种情况下,真的没有多大意义的,因为你每次都返回新的数据。它将使意义,如果你保存结果在一个类的属性,然后返回属性值。 – Artefacto 2010-05-16 18:18:58

相关问题