how grab field value from a PHP query (PDO) - php

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

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

While selecting data from database using following code

I have used this code to select data from table tbl_users but it is showing 1. what does it mean..
require_once('config.php');
$dbCon = getConnection();
$sql = "SELECT * FROM tbl_users";
$stmt = $dbCon->prepare($sql);
print($stmt->execute());
can Anyone Help...????
If the query runs successfully, $stmt->execute() returns true, which will print as 1.
To return data:
//Returns first row as array
$row = $stmt->fetch();
//Returns first row as key => value array
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//Returns all rows as key=>value arrays
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
You can use this to print data like so:
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
//Print all data
$print_r($rows);
//Print data row-by-row
foreach($rows as $row){
print_r($row);
}
At this moment you're printing the response of the query, not the results.
To print the results you should do something like this:
foreach ($stmt as $row) {
print $row['name'] . "\t";
print $row['first_name'] . "\t";
print $row['birth_date'] . "\n";
}
On successful execution of query execute() return True .
$sql = "SELECT * FROM tbl_users";
$stmt = $dbCon->prepare($sql);
$result = $stmt->fetchAll();
print_r($result);

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

pdo fetch within a fetch error

I am trying to run the following script (unsuccessfully):
$variables = $db->query("SELECT * FROM table1 WHERE Session_ID = '$sess1'");
while($row = $variables->fetch()) {
//FETCH DATA
$id= $row["ID"];
$info = $db->query("SELECT * FROM table2 WHERE ID = $id");
while($row2 = $info->fetch()) {
$name = $row2["FNAME"]." ".$row2["LNAME"]; }
$phone = $row2["PHONE"];
}
//SEND CUSTOMER EMAIL
require("../email/email.php");
}
this returns the error: Fatal error: Call to a member function fetch() on a non-object in...
While I am able to "solve" the problem, it is ugly. Essentially I have to make several calls ahead of the one I'm trying below (which in theory should work).
Any ideas?
As far as I can tell, you have to fetch all results from a resultset before you can issue a new query. If you're using MySQL, you can circumvent that by calling $db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);, but I would advice against it, as it makes your code less portable, and on of the major plusses of PDO, database-abstraction, is lost.
try this instead
//prepare the query
$variables = $db->prepare("SELECT * FROM table1 WHERE Session_ID = :sess1");
$info = $db->prepare("SELECT * FROM table2 WHERE ID = :ID");
//bind the variable :sess1 to $sess1
$variables->bindParam(':sess1', $sess1, PDO::PARAM_STR);
//execute the query
$variables->execute;
//fetch the result
$result = $variables->fetch(PDO::FETCH_ASSOC);
//set $result['ID'] to a variable and bind it to the variable :ID in our second query
$id = $result['ID'];
$info->bindParam(':ID', $id, PDO::PARAM_INT);
while($row2 = $info->fetch()) {
$name = $row2["FNAME"]." ".$row2["LNAME"]; }
$phone = $row2["PHONE"];
}
//SEND CUSTOMER EMAIL
require("../email/email.php");
}

Categories