Retrive an array stored in database using PDO - php

I have an array: productid = [1,2]. Now I want to fetch data from product table by using this part of code:
$sql = 'SELECT name FROM product WHERE id=:id';
$s = $pdo->prepare($sql);
foreach($productid as $id)
{
$s->bindValue(':id', $id);
$s->execute();
}
when I returned the names as follow:
foreach($s as $row)
{
$name[] = array(
'name' => $row['name']
);
}
I just got the product name of second id and didn't get both names.
What's the problem?

I just got the product name of second id and didn't get both names. What's the problem?
You've got to put your $name[] = $row['name']; (yes, that's right notation) code inside of the foreach loop, as well as code that actually fetches the data.
You may also form a IN() statement that should be looks like IN (?,?,?,?) and run it in one query. Something like this (not tested):
$in = trim(str_repeat('?,',count($productid)).",");
$sql = "SELECT name FROM product WHERE id IN ($id)";
$stmt = $db->prepare($sql);
$stmt->execute($productid);
$name = $stmt->fetchAll();

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

PDO query not executing in while loop

I am tyring to use PDO to retrieve data from a database.
I can retrieve 'NAME' during the first iteration but not after the 2nd iteration.
my code is as follows:-
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row["ID"];
$query = "SELECT NAME FROM Style_Master WHERE ID=$id";
$stmt = $db->query($query);
$style_name = $stmt->fetch(PDO::FETCH_ASSOC)["NAME"];
echo $style_name; // for first id name is displayed but for next id onwards no style name is displayed.
}
$stmt->fetch(PDO::FETCH_ASSOC)["NAME"]; ?
$style_name = $stmt2->fetch(PDO::FETCH_ASSOC)["NAME"];
I'm supposing that you have a piece of code like this
$queryA = "SELECT id, somethingelse FROM somewhere";
$stmt = $db->query($queryA);
Before the while loop.
At first iteration you fetch the first record resulting from queryA
After you re-assign the same variable $stmt with other records coming from
$query = "SELECT NAME FROM Style_Master WHERE ID=$id";
It happens that at second iteration (assuming there are many NAMEs with same ID otherwise the loop ends), you look for a field "id" into the result-set of query you used to find "name".
So you iterate the query using id=null
The problem with your code is related with the variable scope.
When you do something like this: (see the comments)
<?php
$stmt = 10;
while (0 < $stmt){
// here, I am acessing the outside varialbe $stmt
echo "{$stmt}<br>"; // 10 will be printed
$stmt = 0; // I am modifying the outside variable.
$stmt--; here the outside variable will be -1
echo "{$stmt}<br>"; // will print -1. And loop will end
}
With this, your code should be like this:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row["ID"];
$query = "SELECT NAME FROM Style_Master WHERE ID=$id";
$stmt2 = $db->query($query);
$style_name = $stmt2->fetch(PDO::FETCH_ASSOC)["NAME"];
echo $style_name; // for first id name is displayed but for next id onwards no style name is displayed.
}
This:
$stmt2 = $db->query($query);
Because the outside variable $stmt should not be modified inside your loop.
When you do :
$stmt = $db->query($query);
You are modifying the outside variable and with that, you are changing your loop behavior.

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

Prepared statement LIKE wildcard

I've made a function that accepts a search column, search term and an id number, and am trying to construct a prepared statement and fetch results, and return in json.
Here is what I have:
function searchBooks($searchColumn, $searchTerm, $teacherid) {
$books = array();
$link = connect_db();
$sql = "SELECT * FROM book WHERE teacher_id = ? AND ? LIKE ?";
$searchTerm = "%{$searchTerm}%";
$stmt = $link->stmt_init();
$stmt->prepare($sql);
$stmt->bind_param('iss', $teacherid, $searchColumn, $searchTerm);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_BOTH)) {
$book = new Book();
$book->id = $row['id'];
$book->title = $row['title'];
$book->author = $row['author'];
$book->ar_quiz = $row['ar_quiz'];
$book->ar_quiz_pts = $row['ar_quiz_pts'];
$book->book_level = $row['book_level'];
$book->type = $row['type'];
$book->teacher_id = $row['teacher_id'];
array_push($books, $book);
}
mysqli_stmt_close($stmt);
return json_encode($books);
}
I'm using a test page that passes values that I know should return results (using 'the' as a wildcard and 'title' for search column):
echo searchBooks('title', 'the', 1);
...but I am not getting any results at all... [] output on the test page.
Assume connect_db() retrieves a connection. Assume I'm doing all my error checking and everything in my controller level, and might add stuff like that later. Just trying to get results right now. Thanks in advance for anything you can point out.
searchcolumn cannot be a bind variable. You can't bind table/column names
$sql = sprintf("SELECT * FROM `book` WHERE teacher_id = ? AND `%s` LIKE ?", $searchColumn);
$searchTerm = "%{$searchTerm}%";
$stmt = $link->stmt_init();
$stmt->prepare($sql);
$stmt->bind_param('is', $teacherid, $searchTerm);
It would also be a good idea to whitelist $searchColumn, validating that it really is a column in your book table before executing this
EDIT
And why bother using fetch_array(MYSQLI_BOTH) when you're only using associative values from the array? Using fetch_assoc() would be better, or you could be even cleverer, and use fetch_object(), and then you wouldn't need to populate your Book object property by property
Consider:
while ($book = $result->fetch_object('Book')) {
array_push($books, $book);
}

Categories