简体   繁体   中英

Returning more than one result mysql & php

Hello basically I am trying to return the 3 values that are in category_name table. however this is proving impossible.... When I do the var dump i get array(2) { [0]=> string(3) "one" ["category_name"]=> string(3) "one" } and i dont know what i am doing wrong

$connection = mysql_connect("localhost","admin","");
mysql_select_db("test",$connection);
$result = mysql_query("SELECT category_name FROM category ");
$result2 = mysql_fetch_array ($result);
var_dump ($result2)

You need a loop, since mysql_fetch_array() will only fetch one row at a time:

$cats = array();
while( $row = mysql_fetch_array ($result)) {
    $cats[] = $row;
}

var_dump( $cats); // This will have all three categories in it

The above loops mysql_fetch_array() until there is no data left, adding the rows returned from the DB into the $cats array.

First - you have to switch to mysqli or PDO

Second - you have to loop through your returned data. In your current script you're fetching just one result into your array.

$connection = mysql_connect( "localhost", "admin", "" );
mysql_select_db( "test", $connection );
$result = mysql_query( "SELECT category_name FROM category" );

while( $row = mysql_fetch_array($result) ) {
    echo $row['category_name'], "<br />";
}

You are getting the first row from your result set.

Subsequent calls to mysql_fetch_array will return the next result row.

Try using:

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
   var_dump($row);
}

The issue with the other answers that appears to be confusing the OP is that MYSQL_ASSOC tells mysql_fetch_array to return an array using column names as indexes instead of the default MYSQL_BOTH (which uses numeric and named array indexes).

Hope that helps!

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