Foreach implemented on finding array data finds only one data - php

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

Related

SQL statement works separately, but together it won't

I am trying to fetch user
function getItemName($dbh, $userId) {
$itemId = getItemId($dbh, $userId); // the getItemId() function works
echo "item id is: " . $itemId ; // because I can see the correct result if I echo it
$sql = "SELECT name FROM items WHERE id = :item_id";
$stm = $dbh->prepare($sql);
$stm->bindParam(':item_id', $itemId, PDO::PARAM_INT);
$stm->execute();
$result = $stm->fetch();
return $result['name'];
}
And I get Trying to access array offset on value of type bool on the return $result['name']; line.
The field name exists on the items table so that's not the issue.
Also, when I try to further test it, I change the $sql statement to SELECT * FROM items and then when I do echo $stm->rowCount() it finds the correct number of rows (With the original SQL statement row count is 0)
Can't find out what's causing this
I have 3 suggestions:
Make sure to convert $itemId to integer using intval();
Just before returning the function result validate that the query returned results.
$result = $stm->fetch();
if(!$result){
return null;
}
return $result['name'];
Finally, the more obvious, make sure the itemId you are looking for exists in the DB.

How to store multiple variables returned from a SELECT in arrays of their own - PDO

I'm rewriting all my old mysql code as PDO code but I can't think of a way to store multiple variables returned from a SELECT in arrays of their own.
I can put ONE set of values in a new array as follows:
$stmt1 = $db->prepare("SELECT P_ID
FROM personal
WHERE personal.firstname=:firstname
AND personal.lastname=:lastname");
// Bind
// Execute
// Fetch
// Store
if ($row)
{
foreach ($row as $key)
{
$PIDs[] = $key;
}
}
But in this query I want to put firstnames and secondnames in different arrays:
$stmt2 = $db->prepare("SELECT FirstName, LastName
FROM personal");
In mysql I was doing:
while ($row = mysql_fetch_array($result))
{
$firstnames[] = $row[0];
$lastnames[] = $row[1];
}
Can someone please help? Every sample PDO SELECT I can find only handles one returned field.
Assuming you fetch data from your statement $stmt:
$stmt2 = $db->prepare("SELECT FirstName, LastName FROM personal");
$stmt2->execute();
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
$firstnames[] = $row['FirstName'];
$lastnames[] = $row['LastName'];
}
You want to set the PDO fetch mode so you can reference the 2D array by name and then fetch all of the rows.
$stmt = $dbh->query($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();
More information can be found here.
And then you can use array_column, more information can be found here;
$firstNames = array_column($result, 'FirstName');
$lastNames = array_column($result, 'LastName');

how grab field value from a PHP query (PDO)

Super new to PHP here, only using PHP to create my json data and having a hard time to understand the syntax. Here is some partial code:
All I am trying to do is to retrieve the value '2af8ddda-2be4-11e5-9453-b82a72d52c35' and put it in variable #sharepointID:
function selectWithSharepointID($table, $columns, $where){
try{
//Get Sharepoint file ID first
$stmt = $this->db->prepare("SELECT ID FROM table1 ORDER BY DownloadedTimeStamp DESC LIMIT 1");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
//$data[] = array("ID" => $rows['ID']);
//$sharepointID = $data[0];
//$sharepointID = $rows[0];
$where = array('id'=>$sharepointID);
//$where = array('id'=>'2af8ddda-2be4-11e5-9453-b82a72d52c35'); //this works fine
...
PS: also tried to use print_r and echo but cant see anything in the console.
Thank you
You don't need to fetchAll if you only have one record. Try:
$stmt = $this->db->prepare("SELECT ID FROM table1 ORDER BY DownloadedTimeStamp DESC LIMIT 1");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sharepointID = $row['ID'];
If you have multiple records the fetchAll makes sense but then you iterate through that to get each row, and its values.
For a rough example where I'd use fetchAll...
$stmt = $this->db->prepare("SELECT name, userid FROM users");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
echo 'Name: ' . $row['name'] . ' userid :' . $row['id'];
}
This expression returns array of rows:
$stmt->fetchAll(PDO::FETCH_ASSOC);
So, you can get data from row 0 in your case:
$sharepointID = $rows[0]['ID'];

query mysql database by field and return all occurrences

I have a table in my database that has these fields:
-id
-video_title
-video_article
-video_category
Now, I'd like to query it by video_category and I have tried this code so far:
public function related_videos($current_video_category)
{
$sql = "SELECT * FROM English WHERE video_category = :current_video_category";
$stmt = $this->pdo->prepare($sql);
$result = $stmt->execute(array(":current_video_category" => $current_video_category));
$data = $stmt->fetch(PDO::FETCH_ASSOC);
return $data;
}
The problem is it returns the first occurrence only and I'm not sure how to return all the occurrences of $current_video_category at once.
Any help would be really appreciated.
You only fetch one row:
$data = $stmt->fetch(PDO::FETCH_ASSOC);
If you want to fetch all available rows from the statement, use fetchAll:
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
This returns an array where each element is a row from the query.
You need to put that fetch assoc in while loop to get all data
While($data = $stmt->fetch(PDO::FETCH_ASSOC)){
//process data here
}

How can I get all id's from a database column into one single array?

How can I fetch all the values from columns (like an id column) and put them into an array?
I'm using PDO API and I tried with other code, but it's not working for me.
$STH = $DBH->query('SELECT Tid from Playlist ');
$STH->setFetchMode(PDO::FETCH_OBJ);
$result = $STH->fetch();
while($result = mysql_fetch_array($result)) {
$ids_array[] = $result['Tid'];
}
You can directly return an id array by specifying the PDO::FETCH_COLUMN.
$stmt = $DBH->query("SELECT Tid from Playlist");
$ids_array = $stmt->fetchAll(PDO::FETCH_COLUMN);
You are mixing mysql_* and PDO, which is obviously not going to work.
Just fetchAll() your results and then just merge all rows into one array by simply looping through all rows with array_map() and returning the id, e.g.
$stmt = $DBH->query("SELECT Tid from Playlist");
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
$ids = array_map(function($v){
return $v->Tid;
}, $result);
print_r($ids);

Categories