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';
}
Related
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().
Query is as below
$query = "SELECT password FROM passwordhistory where userid=? order by id desc limit 3";
$stmt2 = $mysqli->prepare($query);
$stmt2->bind_param('i',$id);
$stmt2->execute();
$res=$stmt2->get_result();
while($row=$res->fetch_object()) {
foreach($row as $t->password) {
echo $password[1];
}
}
In the above code I want print password in to three variables. I am not able to do this.
Change your code to this :
$i = 0;
while($row=$res->fetch_object())
{
foreach($row as $t->password)
{
echo $newPass.$i = $password[1];
$i++;
}
}
I think you can use str_split function.
foreach($row as $t->password)
{
$array = str_split($password[1],3);
}
Check the manual here
So I made a query which returns many restaurants and I put them in a variable $row:
<?php if(count($Result_restaurants)>0)
{
foreach($Result_restaurants as $row)
{ ?>
<div id="ForEveryRestaurant">
<?php
$Rest_Name = $row['name'];
//$Rest_Name = $row;
$stmt = $db->prepare("SELECT Restaurant.idRestaurant FROM Restaurant WHERE Restaurant.name = \"$Rest_Name\"");
$stmt->execute();
$idRestaurant = $stmt->fetch();
$avg = 0;
$rateSum = 0;
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
$stmtcard = $db->prepare($strcard);
$stmtcard->execute();
$result = $stmtcard->fetchAll();
if (count($result) === 0)
{
return 0;
}
foreach( $result as $coments)
{
$rateSum += $coments['rating'];
}
$avg = $rateSum / count($result);
$avg = round($avg, 1);
When I try to run my code, it prints Array to string conversion.
The problem appears in this line:
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
I searched about the error and I understand but I tried many resolutions and didn't solved the problem.
can someone help please?
You should do like the following
$stmt->execute();
$stmt->bind_result($idRestaurant);
$stmt->fetch();
Try For PDO:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$idRestaurant = $result['idRestaurant'];
The problem is in this statement
$idRestaurant = $stmt->fetch();
Have you tried $idRestaurant = $stmt->fetch()[0];?
You can actually check what's coming into $idResturant by checking it via var_dump
var_dump($idResturant)
Check this:
$idRestaurant = $stmt->fetch();
// Its an array and you cannot use an array directly with WHERE clause in a query. Convert it to normal variable and use it.
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
// here you are using the array in WHERE clause
To do this:
$rating = isset($stmt->fetch()[0]) ? $stmt->fetch()[0]: null;
I have this code working but only halfway, it is able to return all of the information that I need however on the return, one of the JSON array is returned twice, why is this? I can't seem to figure out why.
Here is my code:
$rows = mysql_num_rows($res);
$array = array();
$i = 0;
while($row = mysql_fetch_array($res, MYSQL_NUM)) {
$array[$i] = (int)$row[0] . "\n";
$i++;
if ($i > $rows){
break;
}
}
$JsonArray = array();
for($i = 0; $i < $rows; $i++){
$q = "SELECT firstName, lastName, email from $mysql_database.$UsersTable WHERE idUser = $array[$i]";
$res = mysql_query($q, $connect) or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
$new_array[] = $row; // Inside while loop
}
$JsonArray[$i] = $new_array;
}
echo json_encode($JsonArray);
This is the result:
All I need is the second and third but somehow I don't know why it is outputting the first twice.
Also, how can I format the result better in the JsonArray?
From what I see you are trying to do, you are trying to fetch your result set from the database for the query.
You need not make use of all those loops. All you have to do is:
$q = "SELECT firstName,lastName,email from $mysql_database.$UsersTable WHERE idUser=$array[$i]";
$res = mysql_query($q,$connect) or die(mysql_error());
$new_array = mysqli_fetch_assoc($res);
mysqli_free_result($res);
You do not need that while loop for each row.
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.';
}