PHP Fetch data twice - php

My function looks like that.
private function generateTree($courseID) {
$q = "SELECT l.id, l.name AS lesson_name, c.name AS course_name FROM lessons AS l, courses AS c WHERE l.course_id=c.id AND c.id=?";
$stmt = $this->db->prepare($q);
$stmt->bind_param("i", $courseID);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $lName, $cName);
echo "<li> <a href='#'>$cName</a> <ul>";
while ($stmt->fetch()) <====HERE!!!
echo "<li> <a href='?course=$courseID&lesson=$id'> $lName </a></li>";
echo "</ul> </li>";
}
}
The problem is that I'm starting to fetch data inside a while condition, but I need it before the while, too. Can I fetch data twice? Any other suggestions?

It's been four years, but in case someone stumble upon this question like I did:
while ($stmt->fetch()) {
// do your thing
}
$stmt->data_seek(0);
while ($stmt->fetch()) {
// do something other
}
You can read documentation here

You can use fetchAll() to fetch all the data and iterate over it as many times as you want.
$result = $stmt->fetchAll(); // PDO
$result = $stmt->fetch_all(); // MySQLi
foreach($result as $row) { print $row['lesson_name']; }
foreach($result as $row) { print $row['lesson_name']; }
foreach($result as $row) { print $row['lesson_name']; }
etc...
Update: I'm not entirely sure what you are doing as you seem to have several ideas mixed into your code. Perhaps you want something like this?
$q = "SELECT l.id, l.name AS lesson_name, c.name AS course_name FROM lessons AS l, courses AS c WHERE l.course_id=c.id AND c.id=?";
$stmt = $this->db->prepare($q);
$stmt->bind_param("i", $courseID);
$stmt->execute();
if ($stmt->num_rows > 0)
{
$results = $stmt->fetch_all();
foreach($results as $row)
{
print_r($row);
}
}

I think you can make your database query class in a way that it returns an array of database result. You can use data as many times you want.
You can make an array of the database-resultset like this:
while($row = mysql_fetch_assoc($result))
{
$results[] = $row;
}

Related

Foreach implemented on finding array data finds only one data

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);
}

how to echo out every item in table using PDO?

I want to echo everything from table that matched the criteria, currently it should be 3 rows that match, but it echoes out only 1.
public function fetchInventoryItems($user_id)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM items WHERE item_owner=?
AND inventory=?");
$stmt->execute([$user_id,'1']);
if ($stmt->rowCount() > 0)
{
while($userRows = $stmt->fetch(PDO::FETCH_ASSOC))
{
$itemId = $userRows['item_id'];
$stmt = $this->db->prepare("SELECT * FROM items_db WHERE
item_id=?");
$stmt->execute([$itemId]);
while($itemRows = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo '<div class="dragcontainer inventory" ><div
id="'.$itemRows['item_id'].'" class="item '.$itemRows['item_type'].'"
style="background-image:url('.$itemRows['item_icon'].')" draggable="true">
</div></div>';
}
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
first fetch should retrieve 3 rows but the while loop only cycles once.
i guess it has something to do with PDO but i dont know what exactly
In the line...
$stmt = $this->db->prepare("SELECT * FROM items_db WHERE item_id=?");
Your overwriting the use of $stmt in the outer loop. Change this and any uses of this version to something else ($stmt1 would do)...
$stmt1= $this->db->prepare("SELECT * FROM items_db WHERE item_id=?");
You could rework both these SQL queries into 1 SQL statement, which would reduce the overhead and stop this sort of issue.

How do I echo out everything in a SQL table?

I'm trying to echo out every single thing in a table from sql, my code is as follows
$stmt = $link->prepare("SELECT * FROM articles");
$stmt->execute();
$stmt->store_result();
if (mysqli_stmt_num_rows($stmt) >= 1) {
$result = mysqli_stmt_get_result($stmt); //get result object
while ($row = mysqli_fetch_assoc($result)){ //get associative array
$news = $row['title'];
}
}
It doesn't work, returning as mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given
I've done my research but literally nothing works :(
You don't need to use prepared statements for this SELECT query as you aren't specifying anything WHERE.
$query = 'SELECT * FROM articles';
if ($result = $link->query($query)) {
while ($row = $result->fetch_assoc()) {
$news = $row['title'];
}
}
For a really good in-depth answer check this out: https://stackoverflow.com/a/11575617/1427345

Checking result/count before outputting while loop

I'm looking for a way to SELECT from database, then check the result, and then output rows in a while loop (IF the result was above zero)
I really want to avoid using a separate count query
Right now I use this:
$sql = 'SELECT id, username, usercity, usercountry FROM siteusers WHERE userage > 50';
$STH = $conn->query($sql);
$arr = $STH->fetchAll();
if (count($arr) > 0) {
echo '<div id="users">';
foreach ($arr as $row) {
echo '<h1>'.$row['username'].</h1>';
}
echo '</div>';
}
It works. But isn't there a way I can check result/numrows and loop the rows, without using fetchAll and custom for-each loop?
Or does it not matter at all? (is for-each just as good as while loop?)
If I do it like this, the first row is not included in the while loop:
$sql = 'SELECT id, username, usercity, usercountry FROM siteusers WHERE userage > 50';
$STH = $conn->query($sql);
if ($row = $STH->fetch()) {
echo '<div id="users">';
while ($row = $STH->fetch()) {
echo '<h1>'.$row['username'].</h1>';
}
echo '</div>';
}
EDIT: I DO need to check the result, for dynamic layout purposes
You can use the PDO method rowCount to verify before your foreach if there are rows
$STH = $conn->query($sql);
if ($STH->rowCount())
{echo '<div id="users">';
foreach ($STH->fetchAll() as $row)
{
echo '<h1>'.$row['username'].'</h1>';
}
echo '</div>';
}
http://php.net/manual/en/pdostatement.rowcount.php
note that this uses up a lot of memory as all your results are loaded at once in memory with fetchAll(). if you have very large result sets, consider using a while instead of the foreach
while ($row = $STH->fetch())
{// foo with $row
}
$row is being set to the first row of your results inside of your if statement. This means that your while loop will start at the second row.
$sql = 'SELECT id, username, usercity, usercountry FROM siteusers WHERE userage > 50';
$STH = $conn->query($sql);
echo '<div id="users">';
while ($row = $STH->fetch()) {
echo '<h1>'.$row['username'].</h1>';
}
echo '</div>';
The while loop will run if there is any results to fetch, and if there aren't, then respectively it won't run.

PDO: Does fetchColumn moves the pointer of the returned results set?

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)
{
...
}
}
}
}
}

Categories