How do I display content with PDO based on num_rows? - php

Apparently, the num_rows property does not work in PDO as it would with mysqli.
Normally, with mysqli, my code would look like this:
<?php
$conn = new mysqli('127.0.0.1','root','mypassword','mydbname');
if($conn->connect_errno){
die("Sorry, could not connect.");
}
$id = 1;
$qry = "SELECT * FROM customers WHERE id = ?";
$getCustomers = $conn->prepare($qry);
$getCustomers->bind_param("i",$id);
$getCustomers->execute();
$result = $getCustomers->get_result();
$count = $result->num_rows;
if($count == 0){
echo "Sorry, there are no results";
}else{
while($row = $result->fetch_object()){
echo $row->id;
echo $row->fname;
echo $row->lname;
echo $row->entry_date;
}
}
?>
How do I create the equivalent with PDO? Here is what I have tried so far:
<?php
try{
$conn = new PDO('mysql:host=127.0.0.1;dbname=mydbname','root','mypassword');
}catch(PDOException $e){
echo $e;
}
$id = 1;
$qry = $conn->prepare("SELECT * FROM customers WHERE id = :id");
$qry->execute([':id'=>$id]);
$rows = $qry->fetchAll(PDO::FETCH_OBJ);
$count = count($rows);
if($count == 0){
echo "Sorry, there are no results for your criteria";
}else{
for($i = 0; $i < $count; $i++){
echo $rows->fname;
}
}
?>

Yeah isn't PDO great ;p no need to count rows when you have already got them.
To loop over your result as you have an array.
Change:
for ($i = 0; $i < $count; $i++){
echo $rows->fname;
}
To:
for ($i = 0; $i < $count; $i++){
echo $rows[$i]->fname;
}
Or better just use a foreach.
foreach ($rows as $row) {
echo $row->fname;
}

The statement
fetchAll(PDO::FETCH_OBJ) returns an array containing all of the result set rows as described here. To get the size of the array use sizeof($count). That should give you the size of the array.

To answer your question specifically. You can use rowCount() to retrieve the number of rows in a result:
$qry = $conn->prepare("SELECT * FROM customers WHERE id = :id");
$qry->execute([':id'=>$id]);
$count = $qry->rowCount();
$rows = $qry->fetchAll(PDO::FETCH_ASSOC); //my personal preference
for($i=0; $i < $count; $i++) {
echo $rows[$i]['fname'];
}
To more closely replicate your mysqli code:
while($row = $qry->fetch(PDO::FETCH_OBJ) {
echo $row->fname;
}
Of course, you should always check $conn->errorCode() after each database execution to ensure something go sideways on you.
UPDATE:
As Lawrence points out, rowCount() does not work with MS SQL Server. An alternative in that case is to use fetchAll() and count().

Related

PHP Mysql fetched data blank

Having a bit of an issue with my php code..
$stmt = $db->prepare("SELECT * FROM mytable WHERE TheGroup = :SearchName ORDER BY TheTime DESC");
$stmt->bindParam(':SearchName', $request, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = count($result);
for ($i = 0; $i < $count; $i++) {
$mTheAvatar = $result[$i]->TheAvatar;
$mTheDirection= $result[$i]->TheDirection;
$mTheGroup = $result[$i]->TheGroup;
$mTheMedia = $result[$i]->TheMedia;
$mTheMessage = $result[$i]->TheMessage;
$mTheSenderName= $result[$i]->TheSenderName;
$mTheThumbImage = $result[$i]->TheThumbImage;
$mTheTime = $result[$i]->TheTime;
$mTheMediaExtension = $result[$i]->TheMediaExtension;
echo "hello";
echo $mTheAvatar;
echo " <- this is avatar";
}
If I do a Var_dump() I see the data being requested without a problem.
If I echo the variables , they are blank..
I have triple checked that the table column names are correct..
the $mTheAvater is a pic in table, if that gives a possible clue, but the rest are blank as well so not sure what is up?!?
You can test:
$mTheAvatar = $result[$i]['TheAvatar'];
As I know in the FETCH_ASSOC it returns data in above structure.
You are trying to read them as if they are objects, but PDOStatement::fetchAll returns an array, so your code should look like:
for ($i = 0; $i < $count; $i++) {
$mTheAvatar = $result[$i]['TheAvatar'];
$mTheDirection= $result[$i]['TheDirection'];
.
.
.
.
echo "hello";
echo $mTheAvatar;
echo " <- this is avatar";
}
If you want to handle objects, you should use PDOStatement::fetchObject
This should be better - 1) it's using foreach; 2) unset(); 3) different structure
$stmt = $db->prepare("SELECT * FROM mytable WHERE TheGroup = :SearchName ORDER BY TheTime DESC");
$stmt->bindParam(':SearchName', $request, PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($results){
foreach($results as $result_data) {
echo $result_data['TheAvatar'];
echo $result_data['TheDirection'];
//and so on
unset($result_data);
}
}
else{
echo 'Empty';
}

mysqli_query(): Empty query in line

I'm confused by xcode and php due to the fact that the exact same code, which works within the iOS simulator, doesn't work for the iPhone itself.
The php file looks like the following:
<?php
$con=mysqli_connect("localhost","BLACKEDOUT","BLACKEDOUT","BLACKEDOUT" );
$array = json_decode($_POST["identifier"]);
for($i=0; $i < count($array); $i++)
{
$name = $array[$i][1];
for($j=0; $j < count($array[$i][0]); $j++)
{
$nummer = $array[$i][0][$j];
$query = "SELECT x FROM Z WHERE uniqueID = $nummer";
$dbConn = new PDO('mysql:host=localhost;dbname=BLACKEDOUT', "BLACKOUT", "BLACKEDOUT");
$smt = $dbConn->prepare($query);
$smt->bindParam(1, $phone_num );
$smt->execute();
if($smt->rowCount())
{
$ergebnisArray[] = [$name,$nummer];
}
else
{
}
}
}
echo json_encode($ergebnisArray);
mysqli_query($con, $query) or die ("Could not connect to server");
mysqli_close($con);
?>
When running the code in the iOS simulator it's all fine, but when I run it on my device it says: as the response string in Xcode: "mysqli_query(): Empty query in on line 30". When I work around that error, I don't get the result I expect either.
Every help is greatly appreciated!
Note, that you use BLACKOUT and BLACKEDOUT mixed, and you never use $con. Also, be aware that you define $query inside a loop, so when it iterates zero times, $query never gets defined, thus cannot by used in mysqli_query.
Try this and come back with the result:
<?php
$array = json_decode($_POST["identifier"]);
for($i=0; $i < count($array); $i++)
{
$name = $array[$i][1];
for($j=0; $j < count($array[$i][0]); $j++)
{
$nummer = $array[$i][0][$j];
$query = "SELECT x FROM Z WHERE uniqueID = '".$nummer."'";
$dbConn = new PDO('mysql:host=localhost;dbname=BLACKEDOUT', "BLACKOUT", "BLACKEDOUT");
$smt = $dbConn->prepare($query);
$smt->bindParam(1, $phone_num );
$smt->execute();
if($smt->rowCount())
{
$ergebnisArray[] = [$name,$nummer];
}
else
{
}
}
}
echo json_encode($ergebnisArray);
?>

Get the number of rows affected by multiple delete

How can I get a count of the number of affected rows when I'm deleting multiple rows in PDO? This is the technique I'm using to delete multiple rows:
$selected = $_POST['checkbox'];
$N = count($selected);
for ($i = 0; $i < $N; $i++) {
$result = $dbh->prepare('DELETE FROM users WHERE id= :id');
$result->bindParam(':id', $selected[$i], PDO::PARAM_INT);
$result->execute();
}
I tried this, but it always returned 1:
$deleted = $result->rowCount();
if ($deleted) {
echo $deleted.' was deleted.';
}
You're running a loop, so each call is deleting 1; you need to add a counter.
So add:
$deleted += $result->rowCount();
inside the loop
and then outside:
if ($deleted) {
echo $deleted.' was deleted.';
}
If the id field is unique, then that statement could affect at most 1 row. However you are preparing a new statement and executing it in a loop. You should try adding up how many you delete.
$deleted = 0;
for ($i = 0; $i < $N; $i++) {
$result = $dbh->prepare('DELETE FROM users WHERE id= :id');
$result->bindParam(':id', $selected[$i], PDO::PARAM_INT);
$result->execute();
$deleted = $deleted + $result->rowCount();
}
echo $deleted.' was deleted.';
Here's a way to do it in 1 delete instead of running multiple deletes.
This way rowCount() will show the actual results deleted.
$selected = $_POST['checkbox'];
$placeholder = array();
$values = array();
foreach ($selected as $id) {
$placeholder[] = ":".$id;
$values[":".$id] = $id;
}
$sql = "Delete FROM users WHERE id IN (".implode(', ',$placeholder).") ";
$result = $dbh->prepare($sql);
$result->execute($values);
$deleted = $result->rowCount();
if ($deleted>0) {
echo $deleted.' was deleted.';
}

MySQLi not returning rows in order

This is probably not a very difficult question to answer. I'm having trouble with this PHP function I wrote... it returns the rows line by line, but it's returning them incremented by 4 each time. So the the 1st row will output, then the 5th, then the 9th...
function showDatabases() {
# $_GET variables from the URL.
$database = mysql_real_escape_string($_GET['database']);
$table = mysql_real_escape_string($_GET['table']);
$mysqli = new mysqli('127.0.0.1', 'root', '', $database);
$query_one = $mysqli->query("SELECT * from $table");
$num_rows = mysqli_num_rows($query_one);
$num_fields = mysqli_num_fields($query_one);
for ($x = 0; $x < $num_rows; $x++) {
for ($c = 0; $c < $num_fields; $c++) {
$row = mysqli_fetch_row($query_one);
echo($row[$c]." ");
}
echo("<br/>");
}
}
Thanks!
mysqli_fetch_row fetched an entire row and moves the pointer to the following row. You should call it only once per each row; now you are calling it once per column.
That is,
for ($x = 0; $x < $num_rows; $x++) {
$row = mysqli_fetch_row($query_one);
for ($c = 0; $c < $num_fields; $c++) {
echo($row[$c]." ");
}
echo("<br/>");
}
you are complicating things
you can do it with just one loop
$query = "SELECT * from $table";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row['fieldname']." ";
}
}
I advice you to add order by some time the default order is not the id order.

Reading only one row from mysql when there are two

I need the script to output both rows. However, I can only get it to output the first one. Help please!
Here is my code:
<?php
$server = ""; // assume server name
$connect = mysqli_connect($server,,,) //assume password etc.
or die ("Couldn't connect to server"); //connect to admin database
$query = "SELECT mt FROM Content";
$result = mysqli_query($connect, $query)
or die ('Could not execute query.');
$nrows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$i = 0;
while ($i <= 30)
{
echo $row[$i];
$i++;
}
?>
You need to fetch into a row in a loop:
while ($row = mysqli_fetch_array($result)) { ...
Try to type:
while( $row = mysqli_fetch_array($result) )
{
echo $row[$i];
$i++;
}
You only fetch the first row.
You should do a while loop on your mysqli_fetch_array() to get both rows.
while ($row = mysqli_fetch_array($result)) {
for ($i = 0; $i < 30; $i++) {
echo $row[$i];
}
}
That should do it (like some of the other posted while I was writing but they forgot parts of the answer :-)
But I think that you should use the OO way of using mysqli.
You could use mysqli_fetch_all() to fetch all of the records.

Categories