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
}
Related
Ive used two queried in a function. FIrst query to find an array of data. And second query is to select rows as per checking the array data from the first query. But the overall function return only one row data.
function getCartItems($conn)
{
$cust_id=$_SESSION['cust_id'];
$stmtSelect1 = $conn->prepare("SELECT product_id FROM tbl_cart WHERE cust_id=cust_id");
$stmtSelect1->bindParam('cust_id',$cust_id);
$stmtSelect1->execute();
$product_id= $stmtSelect1->fetchAll();
foreach($product_id as $productid) {
$stmtfetch = $conn->prepare("SELECT * FROM tbl_item WHERE product_id=:products_id");
$stmtfetch->bindParam(':products_id',$productid['product_id']);
$stmtfetch->execute();
$datas = $stmtfetch->fetchAll();
print_r($datas);
exit();
}
}
First of all, your code has typos (Missing ":" before parameter, product_id/products_id).
This should work:
$cust_id=$_SESSION['cust_id'];
$stmt = $conn->prepare("SELECT tbl_item.* FROM tbl_cart, tbl_item WHERE tbl_cart.cust_id = :cust_id AND tbl_item.product_id = tbl_cart.product_id);
$stmt->bindParam('cust_id',$cust_id);
$stmt->execute();
$rows = $stmt->fetchAll();
foreach($rows as $row)
{
print_r($row);
}
I am trying to collect all rows from a table of mySql database. But I am getting 1 row lesser than the original rows. Suppose the table has 3 rows but I am getting data of 2 rows. I am missing the first one always. Here is the image of my table.
Here is my code:
$query = $db->query("SELECT * FROM `POS_refund`");
if($query->fetchColumn() > 0){
foreach($query as $row){
echo $get_prod_id = $row['prod_id'];
$get_prod_qnt = $row['qnt'];
}
}
Where is the fault?
PDOStatement::fetchColumn Returns a single column from the next row of a result set
You should use fetch() or fetchall() in your case
<?php
$query = $db->query("SELECT * FROM `POS_refund`")->fetchall();
foreach($query as $row){
echo $get_prod_id = $row['prod_id'];
$get_prod_qnt = $row['qnt'];
}
?>
If you want to see if there's records returned you could use count() since fetchall() returns array, then just count your array elemenets
<?php
$query = $db->query("SELECT * FROM `POS_refund`");
$results = $query->fetchall();
if(count($results) > 0){
foreach($results as $row){
echo $get_prod_id = $row['prod_id'];
$get_prod_qnt = $row['qnt'];
}
}else{
echo "No results";
}
?>
I would use a while loop. it would look like this:
while ($row = $query->fetchall) {
echo $get_prod_id = $row['prod_id'];
$get_prod_qnt = $row['qnt'];
}
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();
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']);
I recently implemented PDO and noticed that my query results lacked the first row. That's probably because fetchColumn() retrieves the first row and moves the pointer to the second row so that the while() loop starts at row 2. Is that correct? If so, how can I avoid that and improve the following code block?
$STH = $DBH->prepare("SELECT * FROM users");
$result = $STH->execute();
if (!$result)
{
return false;
}
elseif($STH->fetchColumn()>0)//counterpart of mysql_num_rows()
{
while ($row = $STH->fetch())
{
...
}
}
}
Is that correct?
Yes. Also, fetchColumn() is not an equivalent for mysql_num_rows(). Instead, fetchColumn() retrieves the indexed column value (defaulting to index 0) of the current row and as assumed, advances the cursor.
If you need a count of the number of rows returned in your query, I suggest you first issue a SELECT COUNT(1) ... query with the same conditions, using fetchColumn() to return the count.
See example #2 on this manual page - http://www.php.net/manual/en/pdostatement.rowcount.php
For example
$stmt = $DBH->query('SELECT COUNT(1) FROM users');
// using a straight PDO::query() call as a prepared statement would be
// overkill for these queries
if ($stmt->fetchColumn() == 0) {
return false;
}
$stmt = $DBH->query('SELECT * FROM users');
while ($row = $stmt->fetch()) {
...
}
After googling around I came up with this solution:
$STH = $DBH->prepare("SELECT * FROM users");
if(!$STH)
{
$error = $DBH->errorInfo();
}
else
{
$result = $STH->execute();
if($result===false)
{
return false;
}
else
{
$rows = $STH->fetchAll(PDO::FETCH_ASSOC);
if(count($rows) > 0)
{
foreach ($rows as $row)
{
...
}
}
}
}
}