check result from prepared statements PDO? - php

I use this code to get rows from database.
// Prepare WC statement
$queryUP = $pdo->prepare("SELECT * FROM unitprices WHERE id_quot = :idQuotation");
// Execute Unit prices statement
$queryUP->execute(array(
'idQuotation' => $idQuotation
));
// How to check the results is empty or not ?
if (results) {
// foreach($queryUP as $rowup) {
//...
// }
} else {
// do another thing
}
I don't how to do to check if there is some results in the query before continuing the code ?

$queryUP = $pdo->prepare("SELECT * FROM unitprices WHERE id_quot = ?");
$queryUP->execute(array($idQuotation));
//here you go
$results = $queryUP->fetchAll();
if ($results) {
// foreach($results as $rowup) {
//...
// }
} else {
// do another thing
}
Hope you are doing your foreach in the template, not right in place as shown here.

If your memory allows you, you can fetch all:
$queryUP = $pdo->prepare("SELECT * FROM unitprices WHERE id_quot = :idQuotation");
$queryUP->bindParam(':idQuotation', $idQuotation, PDO::PARAM_STR);
$queryUP->execute();
$result = $queryUP->fetchAll(PDO::FETCH_ASSOC);
if (count($result) > 0) {
} else {
}

Related

How to get multiple rows from mysql & PHP with this function

I have this function which returns only one row, How can I modify the function so that it returns more than one row?
public function getVisitors($UserID)
{
$returnValue = array();
$sql = "select * from udtVisitors WHERE UserID = '".$UserID. "'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
There is a function in mysqli to do so, called fetch_all(), so, to answer your question literally, it would be
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ".intval($UserID);
return $this->conn->query($sql)->fetch_all();
}
However, this would not be right because you aren't using prepared statements. So the proper function would be like
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $UserID);
$stmt->execute();
$res = $stmt->get_result();
return $res->fetch_all();
}
I would suggest storing them in an associative array:
$returnValue = array();
while($row = mysqli_fetch_array($result)){
$returnValue[] = array('column1' => $row['column1'], 'column2' => $row['column2']); /* JUST REPLACE NECESSARY COLUMN NAME AND PREFERRED NAME FOR ITS ASSOCIATION WITH THE VALUE */
} /* END OF LOOP */
return $returnValue;
When you call the returned value, you can do something like:
echo $returnValue[0]['column1']; /* CALL THE column1 ON THE FIRST SET OF ARRAY */
echo $returnValue[3]['column2']; /* CALL THE column2 ON THE FOURTH SET OF ARRAY */
You can still call all the values using a loop.
$counter = count($returnValue);
for($x = 0; $x < $counter; $x++){
echo '<br>'.$rowy[$x]['column1'].' - '.$rowy[$x]['column2'];
}

Pdo Sqlite and php

I have a question related to php / pdo and sqlite. I have ported some code from a mysql backend to a sqlite backend. I have used rowCount() alot in this project.
In my original Mysql application i did this:
$stmt = $db->query("SELECT id FROM table where id = $id ");
$rc = $stmt->rowCount();
if ($rc == 1) {
// do something
}
The documentation says this method is only for returning affected rows from UPDATE, INSERT, DELETE queries, with the PDO_MYSQL driver (and this driver only) you can get the row count for SELECT queries.
So, how to achive the same thing with a sqlite backend?
This is how I have ended up doing it:
$stmt = $db->query("SELECT count(id) as cnt FROM table where id = $id ");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($row['cnt'] == "1") {
// do something
} else {
return false;
}
}
}
I am looking for a more elegant solution, while achieving the same thing as rowCount().
This is the way to do that in pdo:
$stmt = $db->query('SELECT * FROM table');
if ($stmt->rowCount() == 1) {
//...
} else {
//...
}
echo $row_count.' rows selected';
(The same way XD)
BTW, I wouldn't recommend doing something like
$stmt = $db->query("SELECT count(id) as cnt FROM table where id = $id ");
It's not good to have variables in statements like that. use something like:
$stmt = $db->query('SELECT id FROM table where id = ?');
$stmt->execute(array($id));
if ($stmt->rowCount() == 1)
{
$arr = $stmt->fetch(PDO::FETCH_ASSOC);
foreach($arr as $element)
{
echo '<pre>'.print_r($element).'</pre>';
}
}
else
{
//...
}
This is part of some code I'm using:
$stmt = $db->prepare('SELECT * FROM users WHERE id=?');
$stmt->execute(array($id));
if ($stmt->rowCount() == 1) {
$currentUser = $stmt->fetchAll(PDO::FETCH_ASSOC)[0];
} else {
return false;
}
Edit: (for compatibility issues)
$stmt = $db->query('SELECT * FROM table');
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (($arr === false) || (sizeof($arr) == 0)) {
return false;
} else {
//... do ....
echo sizeof($arr);
}

SELECT RECORDS INTO ARRAY

I'm neubie with PHP. I need to build some Web Service so, I have problems.. please help me.
I have this code, I have to put in array the Select's records and the return in JSON.
The CODE...
function redeem() {
// Check for required parameters
if (isset($_POST["id_cliente"]) && isset($_POST["id_sucursal"])) {
// Put parameters into local variables
$cliente = $_POST["id_cliente"];
$sucursal = $_POST["id_sucursal"];
$stmt = $this->db->prepare('SELECT id_arbitro FROM arbitro WHERE id_cliente =? AND id_sucursal =?') or die(mysqli_error($this->db));
$stmt->bind_param("ii", $cliente, $sucursal);
$stmt->execute();
//$stmt->bind_result($id_arbitro);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$cuantos = count($result);
echo "$cuantos";
$registros = 0;
/*while ($stmt->fetch()) {
$registros ++;
// Return unlock code, encoded with JSON
$result = array("id_arbitro" => $stmt,);
echo "$id_arbitro !";
}
*/
$stmt->close();
if ($registros < 0) {
sendResponse(400,"No existen arbitros con los parĂ¡metros recibidos");
return false;
}
//echo json_encode($result);
sendResponse(200, "FIN");
//printf("ERROR %s",$registros);
return true;
}
sendResponse(400, 'Invalid request');
return false;
}
To encode the results of your query, use something like that
$statement=$pdo->prepare("SELECT * FROM table");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
Based on your comment, you're having trouble understanding how to put them all into an array.
First, make sure that whatever you use for database calls doesn't already have a fetchAll style function that could do this for you.
If you still need to do, you need to define an array first and then add to it:
$results = array();
while ($record = $stmt->fetch()) {
$registros ++;
$results[] = $record;
}
print json_encode($results);
The syntax might vary slightly for your database class but this gives you an idea.

Checking for an empty result (PHP, PDO, and MySQL) [duplicate]

This question already has an answer here:
How to check fetched result set is empty or not?
(1 answer)
Closed 11 months ago.
What am I doing wrong here? I'm simply retrieving results from a table and then adding them to an array. Everything works as expected until I check for an empty result...
This gets the match, adds it to my array and echoes the result as expected:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today', $today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
return true;
When I try to check for an empty result, my code returns 'empty', but no longer yields the matching result:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today',$today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
if ($sth->fetchColumn()) {
echo 'not empty';
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
return true;
}
echo 'empty';
$db = null;
return false;
You're throwing away a result row when you do $sth->fetchColumn(). That's not how you check if there are any results. You do
if ($sth->rowCount() > 0) {
... got results ...
} else {
echo 'nothing';
}
Relevant documentation is here: PDOStatement::rowCount
If you have the option of using fetchAll() then, if there are no rows returned, it will just be an empty array.
count($sql->fetchAll(PDO::FETCH_ASSOC))
will return the number of rows returned.
You should not use rowCount for SELECT statements as it is not portable. I use the isset function to test if a select statement worked:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
// I would usually put this all in a try/catch block, but I kept it the same for continuity
if(!$sth->execute(array(':today'=>$today)))
{
$db = null;
exit();
}
$result = $sth->fetch(PDO::FETCH_OBJ)
if(!isset($result->id_email))
{
echo "empty";
}
else
{
echo "not empty, value is $result->id_email";
}
$db = null;
Of course this is only for a single result, as you might have when looping over a dataset.
I thought I would weigh in as I had to deal with this lately.
$sql = $dbh->prepare("SELECT * from member WHERE member_email = '$username' AND member_password = '$password'");
$sql->execute();
$fetch = $sql->fetch(PDO::FETCH_ASSOC);
// if not empty result
if (is_array($fetch)) {
$_SESSION["userMember"] = $fetch["username"];
$_SESSION["password"] = $fetch["password"];
echo 'yes this member is registered';
}else {
echo 'empty result!';
}
what I'm doing wrong here?
Almost everything.
$today = date('Y-m-d'); // no need for strtotime
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today',$today); // no need for PDO::PARAM_STR
$sth->execute(); // no need for if
$this->id_email = $sth->fetchAll(PDO::FETCH_COLUMN); // no need for while
return count($this->id_email); // no need for the everything else
Effectively, you always have your fetched data (in this case in $this->id_email variable) to tell whether your query returned anything or not. Read more in my article on PDO.
One more approach to consider:
When I build an HTML table or other database-dependent content (usually via an AJAX call), I like to check if the SELECT query returned any data before working on any markup. If there is no data, I simply return "No data found..." or something to that effect. If there is data, then go forward, build the headers and loop through the content, etc. Even though I will likely limit my database to MySQL, I prefer to write portable code, so rowCount() is out. Instead, check the the column count. A query that returns no rows also returns no columns.
$stmt->execute();
$cols = $stmt->columnCount(); // no columns == no result set
if ($cols > 0) {
// non-repetitive markup code here
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
I only found one way that worked...
$quote = $pdomodel->executeQuery("SELECT * FROM MyTable");
//if (!is_array($quote)) { didn't work
//if (!isset($quote)) { didn't work
if (count($quote) == 0) { //yep the count worked.
echo 'Record does not exist.';
die;
}
Thanks to Marc B's help, here's what worked for me (note: Marc's rowCount() suggestion could work too, but I wasn't comfortable with the possibility of it not working on a different database or if something changed in mine... also, his select count(*) suggestion would work too, but, I figured because I'd end up getting the data if it existed anyway, so I went this way).
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today', $today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
if (count($this->id_email) > 0) {
echo 'not empty';
return true;
}
echo 'empty';
return false;

Mysqli Multi Query - Sort Results

i want to save every result from an sql statement in a differen array. I tried:
$sql = "SELECT * FROM `link_server` WHERE `in_use` = false;";
$sql .= "SELECT * FROM `link_queue` WHERE `active` = false;";
if ($db->multi_query($sql))
{
do
{
// Erstes Abfrageergebnis ausgeben
if ($result = $db->store_result())
{
// Abfrageergebnis ausgeben
while ($server_fetch = $result->fetch_array())
{
$server[] = $server_fetch;
}
$result->close();
}
// Trenner fuer Zweites Abfrageergebnis
if ($db->more_results())
{
echo "<hr />test";
$queue[] = $server_fetch;
}
} while ($db->next_result());
echo "Servers:";
print_r($server);
echo "Queue:";
print_r($queue);
}
The result from the first statement should be saved in the array $server, and the second should be saved in the array $queue.
The above example stores the complete return (from both statements) in the first array ($server). The second array is empty.
How can i solve that?
Thanks for your help!
$db->more_results() is a way of flagging that the end of the results of a query have been reached, not to get the next set of results. You can use it to tell your loop to start loading the next array - for example by setting a flag.
if ($result = $mysqli->store_result()) {
while ($server_fetch = $result->fetch_row()) {
if (!$second) {
$server[] = $server_fetch;
} else {
$queue[] = $server_fetch;
}
}
$result->close();
}
/* next set of results */
if ($mysqli->more_results()) {
$second = true;
}
Alternatively, you could use a variable variable like so:
/* set up variables */
$server = array();
$queue = array();
$active = 'server';
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store result set */
if ($result = $mysqli->store_result()) {
while ($server_fetch = $result->fetch_row()) {
${$active}[] = $server_fetch;
}
$result->close();
}
/* next set of results */
if ($mysqli->more_results()) {
$active = 'queue';
}
} while ($mysqli->next_result());
}
Although I have to concur with the commentors, this adds a lot of effort and additional code complexity to an otherwise simple pair of requests.

Categories