SELECT * FROM `users` returns only first user - php

I have a php script:
$sql = $db->query("SELECT * FROM `users`");
$row = $sql->fetch();
foreach($row as $value){
echo $value . "<br>";
}
Database 'users' contains 29 records, but I'm getting this:

This is because you're only fetching one record.
Try your code like this:
$sql = $db->query("SELECT * FROM `users`");
$row = $sql->fetchAll();
foreach($row as $value){
print_r($value);
echo "<br>";
}
this way you'll get an array of results, so you loop over the array instead of over the properties.

fetch() returns single elements. Instead try with fetchAll
$row = $sql->fetchAll();
fetchAll — Returns an array containing all of the result set rows
it will return an array hence, remove echo $value and use print_r($value)
fetch — Fetches the next row from a result set only 1 row

mysql fetch() function fetches the next row from a result set only 1 row, whereas mysql fetchAll() function returns an array containing all of the result set rows.
So use fetchAll() to get all the records from resultset, replace this line
$row = $sql->fetch();
with
$row = $sql->fetchAll();

Related

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']);

incorrect result display from database

I have a database table that has 4 records with a column _id that auto increments. When I run a query to get all records, it works but it doesn't echo out all the ids, it only points to the first rows and echos it four times. I am using PHP and MySQLi. Here is my code
Code for querying
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
Code for display
do{
echo result['_id'];
}while($query->fetch_assoc());
It outputs 1111 instead of 1234. Please what is wrong?
You're fetching each of the 4 results, so it loops the appropriate number of times; but you're only assigning the fetched result to $result once, so that's the only _id value that gets echoed
do{
echo $result['_id'];
}while($result = $query->fetch_assoc())
You also can use a foreach loop :
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
foreach($result as $data){
echo $data['_id'];
}

SQL only retrieve first item in the database

$search = mysql_query("SELECT subject FROM book WHERE useid = $userid") or die(mysql_error());
$sub = mysql_fetch_array($search, MYSQL_ASSOC);
print_r($sub);
There's a lot of subject in the book table with same user id, but it only retrieve first of it, why is that so?
mysql_fetch_array returns array representation of current row only:
Fetch a result row as an associative array, a numeric array, or both
You have to use loop to iterate over all returned rows:
$search = mysql_query("SELECT subject FROM book WHERE useid = $userid") or die(mysql_error());
while($sub = mysql_fetch_array($search, MYSQL_ASSOC)) {
print_r($sub);
}
You have to parse result of this
while($sub = mysql_fetch_array($search, MYSQL_ASSOC)){
print_r($sub);
}
Reason for this
mysql_fetch_array function returns an associative array, but it also returns FALSE if there are no more rows to return! Using a PHP While Loop we can use this information to our advantage.
If we place the statement "$row = mysql_fetch_array()" as our while loop's conditional statement we will accomplish two things:
We will get a new row of MySQL information that we can print out each time the while loop checks its conditional statement.
When there are no more rows the function will return FALSE causing the while loop to stop!
Hence it will continue to print data until the function returns false
As mysql* are officially depreciated you should be using mysqli* or prepared statements
//$Conn = new mysqli(host, username, pass, db);
$sqlquery = "SELECT subject FROM book WHERE useid = $userid";
//Execute the query reurns data into a $result
$result = $Conn->query($sqlquery);
//results into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
print_r($resultArray);
OR PDOStatement::fetchAll
<?php
$sth = $dbh->prepare("your query");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>

SQL query only display first result

the code below display the row 116 twice, it won't display row 118. Any idea how to solve this issue?
$data = mysql_query("SELECT * FROM item WHERE dcid IN('116','118')")
or die(mysql_error());
$info = mysql_fetch_array($data);
foreach ($info as $item) {
echo($item);
}
mysql_fetch_array only fetches a single row. Typically it is used in a while loop to cycle through all the results.
To continue your example above:
$data = mysql_query("SELECT * FROM item WHERE dcid IN('116','118')") or die(mysql_error());
while ($item = mysql_fetch_array($data)) {
echo($item)
}
your query must be as:
$data = mysql_query("SELECT * FROM item WHERE dcid IN('116','118')") or die(mysql_error());
while ($item = mysql_fetch_array($data)) {
echo $item['column_name1'];
} echo $item['column_name2'];
mysql_fetch_array returns a single row in an array like this that contains both an associative array and a regular numeric-keyed result set of your row.
0=> column,
column=>column
Thats why it returns twice in foreach.Use it like this
mysql_fetch_array($result, MYSQL_ASSOC);
Also, if dcid is your key and it's autoincrementing ( ID for rows ) you can also use LIMIT 116,118.
For more info: http://php.about.com/od/mysqlcommands/g/Limit_sql.htm
use group by as this
$data =mysql_query("SELECT * FROM item WHERE dcid IN('116','118') group by dcid")
or die(mysql_error());

PDO Bug: fetchColumn() VS count()

I have a table containing 3 rows. I am trying to loop through all the rows but I am not getting the right amount of rows.
My code is as follow:
$result1_prepare = $DB->prepare("SELECT * FROM table");
$result1_prepare->execute();
$num = $result1_prepare->fetchColumn();
$result1 = $result1_prepare->fetchAll();
echo $num; //OUTPUT 3
echo count($result1); //OUTPUT 2
if($num > 0){
foreach ($result1 as $x => $row) {
//LOOPING only 2 times, 1 row is not showing
}
}
The fetchAll() function is only returning 2 rows. How come?
Your code contradicts with your words. most likely you are calling fetchColumn before fetchAll - so, fetchColumn snatches one row from the resultset, leaving only two for fetchAll.
Anyway, you need none of these
$stm = $DB->prepare("SELECT * table");
$stm->execute();
$data = $stm->fetchAll();
foreach ($data as $x => $row) {
//LOOPING only if there was data returned. no need to check the number
}

Categories