简体   繁体   中英

Double output from mysql. I wonder what I am doing wrong

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
*/

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() .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM