Reputation: 405
I am getting a double output from mysql. I am using a resource for the columns and another for the rows, and a for loop.
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
*/
Upvotes: 1
Views: 120
Reputation: 1383
This line is crucial $result = mysql_fetch_array($select_resource);
You could use mysql_fetch_assoc($select_resource)
and that's it.
Another thing is that mysql_num_rows
would be more appropriate. 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.
Upvotes: 0
Reputation: 882806
As per the docs, the default is to fetch both the numeric and the associative array.
If you want just one of them, add a second parameter to your mysql_fetch_array()
call, such as:
$result = mysql_fetch_array($select_resource,MYSQL_ASSOC);
And be aware, you're actually storing the number of columns in your num_rows
variable. You should be using mysql_num_rows()
.
Upvotes: 1