简体   繁体   中英

why select * from return only the first field?

I'm making the next query to the db

$result = $con->query ( 'select * from table');
$datos = $result->fetch_assoc();
echo "Cantidad de datos: ".count($datos).",";
print_r($datos);

Should show an array with all the entries, but only show the first entry. Why?

PS: i saw other posts but i haven't limit or joins.

fetch_assoc fetches a result row as an associative array

So you could go through all the rows with a while cycle that fetches another row if possible.

$count = 0;
while( $row = $result->fetch_assoc() ){
    // You can access data like this -->> $row['data'];
    $count++;
}
echo $count;

and after you are done, you should free your memory associated with the result

$result->free();

But if you'd like to get count only, you could use mysql_num_rows that returns number of rows from result set.

$count = mysql_num_rows($result);
echo $count;

fetch_assoc returns only one row when you are doing $datos = $result->fetch_assoc(); You can fetch the entire array in both PDO and mysqli , Here is a example to fetch all rows using the mysqli->fetch_all function, hope this helps!

//Database Connection
$sqlConn =  new mysqli($hostname, $username, $password, $database);

//Build SQL String
$sqlString = "SELECT * FROM my_table";

//Execute the query and put data into a result
$result = $this->sqlConn->query($sqlString);

//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);

//Copy result into a numeric array
$resultArray = $result->fetch_all(MYSQLI_NUM);

//Copy result into both a associative and numeric array
$resultArray = $result->fetch_all(MYSQLI_BOTH);

Please always refer to the manual of the framework you are using. fetch_assoc();Fetches a result row as an associative array. If you want to fetch all the rows, use a while statement like so:

    $result = $c->query('SELECT user,host FROM mysql.user');
    while ($row = $result->fetch_assoc()) {
    printf("'%s'@'%s'\n", $row['user'], $row['host']);

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