[英]Double output from mysql. I wonder what I am doing wrong
I am getting a double output from mysql. 我从mysql获得双输出。 I am using a resource for the columns and another for the rows, and a for loop.
我正在为列使用资源,为行使用另一个资源,并使用for循环。
function selectItems($table)
{
$resultado='';
$select_resource = mysql_query("SELECT * FROM ".$table);
$num_rows = mysql_num_fields($select_resource);
for($i=0;$i<$num_rows;$i++){
$result = mysql_fetch_array($select_resource);
foreach($result as $key=>$var)
{
$resultado .="$key: $var<br/>\n";
}
$resultado .="<hr />";
}
return $resultado;
}
This is the test 这是测试
$data = new Db();
$data->connect(HOST, USER, DB, PASSWORD);
echo $data->selectItems("comments");
$data->closeDb();
And this is the output 这是输出
/*
0: 1
id: 1
1: name
username: name
2: Content
comment: Content
3: 000.000.000.000
ip: 000.000.000.000
4: It’s impressive how popular content management i
title: It’s impressive how popular content management i
5: freemind
avatar: freemind
*/
As per the docs , the default is to fetch both the numeric and the associative array. 根据docs ,默认值是同时获取数字数组和关联数组。
If you want just one of them, add a second parameter to your mysql_fetch_array()
call, such as: 如果只需要它们之一,则在您的
mysql_fetch_array()
调用中添加第二个参数,例如:
$result = mysql_fetch_array($select_resource,MYSQL_ASSOC);
And be aware, you're actually storing the number of columns in your num_rows
variable. 请注意,您实际上是在
num_rows
变量中存储列数。 You should be using mysql_num_rows()
. 您应该使用
mysql_num_rows()
。
This line is crucial $result = mysql_fetch_array($select_resource);
这行至关重要。
$result = mysql_fetch_array($select_resource);
You could use mysql_fetch_assoc($select_resource)
and that's it. 您可以使用
mysql_fetch_assoc($select_resource)
就是这样。
Another thing is that mysql_num_rows
would be more appropriate. 另一件事是
mysql_num_rows
更合适。 It would pull all the data. 它将提取所有数据。 In your case it will lack one record, sadly.
可悲的是,您的情况将缺少一项记录。
I would suggest you to switch to MySQLi, or PDO of course but in your case this is a correct solution. 我建议您当然要切换到MySQLi或PDO,但是对于您而言,这是正确的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.