创建MySQL查询PHP数组 [英] create array from mysql query php
问题描述
我有一个小问题,我不明白。我有一个具有所有者和类型(更偏离轨道)的DB。我想获得的所有类型值的列表具有所有者等于当前用户,但我只得到两个结果
I have a little problem that I don't understand. I have a db that has an owner and type (and more off course). I want to get a list of all the type values that has owner equal to the current user, but I get only two result
$sql = "SELECT type FROM cars WHERE owner='".mysql_real_escape_string($_SESSION['username'])."' AND selling='0' ORDER BY id DESC ";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_array($result));
打印出:
Array ( [0] => 18 [type] => 18 )
和
$sql = "SELECT type FROM cars WHERE owner='".mysql_real_escape_string($_SESSION['username'])."' AND selling='0' ";
打印出:
Array ( [0] => 16 [type] => 16 )
和结果应该是像19,19,18,17,16在数组中。那是一切有我的设置为所有者的类型。
And the result should be something like 19, 19, 18, 17, 16 in an array. Thats all the types that has me as set as owner.
我有现在这样的工作:
for ($x = 0; $x < mysql_num_rows($result); $x++){
$row = mysql_fetch_assoc($result);
echo $row['type'];
}
下面我打印出所有的值正确,但我需要创建的所有值的数组。不过,我觉得我可以用array_push,但最多可以做的更好的方法。我想我会得到所有用一个简单的MySQL查询类型的值。
Here I print out all the values correctly, but I need to create an array with all the values. I though I could use array_push, but there most be a better way of doing it. I thought I would get all the type values with a simple mysql query.
推荐答案
很多时候,这是在,而
循环中完成:
Very often this is done in a while
loop:
$types = array();
while(($row = mysql_fetch_assoc($result))) {
$types[] = $row['type'];
}
看一看在文档的例子。
的 mysql_fetch _ *
方法总是会得到的下次的结果集的元素:
The mysql_fetch_*
methods will always get the next element of the result set:
如果没有更多的行,则返回字符串数组,对应于所取出的行,或FALSE。
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
这就是为什么,而
循环的作品。如果没有任何行了 $行
将假
和,而
环路存在。
That is why the while
loops works. If there aren't any rows anymore $row
will be false
and the while
loop exists.
它只是似乎 mysql_fetch_array
获取多个行,因为默认情况下它得到的结果作为的正常的和的作为关联值:
It only seems that mysql_fetch_array
gets more than one row, because by default it gets the result as normal and as associative value:
通过使用MYSQL_BOTH(默认),你会得到与两个关联和数字索引。
By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.
您的例子最好的说明它,你会得到相同的值 18
键,您可以通过 $访问v [0]
或 $ v ['类型']
。
Your example shows it best, you get the same value 18
and you can access it via $v[0]
or $v['type']
.
这篇关于创建MySQL查询PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!