How to user fetch_array with prepared statements in Mysqli? - php

Okay, I know there are a number of posts on this one, but I am still posting this questions because none of them are working yet.
I am trying to fetch result data with mysqli where the row count is fetching fine,but the row data is not.
Here is my code:
$query = $db->prepare("SELECT * from users where email = ?");
$query->bind_param("s",$loginEmail);
$query->execute();
$query->store_result();
$row_count = $query->num_rows;
echo $row_count;
if($row_count==1){
$row = $query->get_result;
$email = $row['email'];
echo $email;
}
So echoing out $rowcount gives the correct result, but I am not able to fetch the subsequent data for this row using fetch_array(). It displays nothing. I know I am going wrong somewhere. Any suggestions would be of great help.

You cannot use get_result() and store_result() at the same time.Besides, it's just superfluous.
$query = $db->prepare("SELECT * from users where email = ?");
$query->bind_param("s",$loginEmail);
$query->execute();
$res = $query->get_result();
$row = $res->fetch_assoc();
if ($row) {
$email = $row['email'];
echo $email;
}

Related

MySQLi not returning fetched data

I have a PHP script that queries the database and returns a list of all the usernames in my database. Problem is, it is not printing anything and I think I am doing the while statement incorrectly, this is my code below:
<?php
include "init.php";
$stmt = "SELECT username FROM tbl_users ";
$result = $dbcon -> prepare($stmt);
$result->execute();
$result->store_result();
$count = 0;
while($row = mysqli_fetch_assoc($result)){
if($row['username']=="Ben"{
echo "Here";
}
//$count++;
}
?>
Even something as basic as this doesn't work:
<?php
include "init.php";
$stmt = "SELECT username FROM tbl_users ";
$result = $dbcon -> prepare($stmt);
$result->execute();
$result->store_result();
$count = 0;
while($row = mysqli_fetch_assoc($result)){
echo "Here";
//$count++;
}
?>
I can't also seem to increment the count too and it is not even printing the basic "Here"
The main problem is that you are not reading manual/examples properly.
mysqli_stmt_get_result() doesn't change the state of a statement. It returns a mysqli result. So you have to assign this returned value to a variable and than use this one.
Besides, you are using a database completely wrong way. Instead of selecting all rows from database you should always select the only data you need.
For your case the code would be like this.
include "init.php";
$name = "Ben";
$stmt = $dbcon->prepare("SELECT 1 FROM tbl_users WHERE username = ?");
$stmt->bind_param("s", $name);
$stmt->bind_result($found);
$stmt->execute();
$stmt->fetch();
if ($found) ... // here you go
For other cases you have to read the manual or a book carefully. and reproduce the code exactly.
Since there are multiple error in your code i managed to write a code am not sure following is best but it works
<?php
include "init.php";
$stmt = "SELECT username FROM tbl_users ";
$result = mysqli_query($sqlconnection, $stmt) or die($mysqli_load->error);
$count = 0;
while($row = mysqli_fetch_assoc($result)){
if($row['username']=="ben"){
echo "Here";
}
//$count++;
}
?>
few errors i found in your code are ) is missing here if($row['username']=="Ben"{ next to "ben"){
and use this type of connection
$link = new mysqli("localhost","user","pass","database");

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

PHP PDO - incremental for loop that fetches the next array row with each loop

I'm in the process of updating my old mysql database techniques to prepared pdo statements. I'm all good with while loops while($row = $result->fetch()) however how would I do the following with PDO prepared statements?
$sql = "SELECT * FROM table WHERE id=".$id;
$result = mysql_query($sql) or die(mysql_error());
$loop_count = mysql_num_rows($result);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = mysql_fetch_array($result);
echo $loop_row['field'];
}
I've tried this but with no joy:
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_count = $result->rowCount();
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = $result->fetch();
echo $loop_row['field'];
}
Thanks!
UPDATE: The reason for using a for loop instead of a while loop is the ability to paginate the results, otherwise I would just put LIMIT 7 on the end of the SQL query.
To properly count rows with PDO you have to do this -
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$rows = $result->fetch(PDO::FETCH_NUM);
echo $rows[0];
But you would be better off using LIMIT in your query if all you want to do is get a static number of results.
In addition you're making your loop overly complex, there is no need to test for a range in the for condition just set the static number unless you're doing something weird, like possibly pagination.
You can try it this way:
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_rows = $result->fetchAll();
$loop_count = count($loop_rows);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
echo $loop_rows[$row]['field'];
}
As requested by the OP, here's an example of PDO prepared statements using LIMIT and OFFSET for pagination purposes. Please note i prefer to use bindValue() rather than passing parameters to execute(), but this is personal preference.
$pagesize = 7; //put this into a configuration file
$pagenumber = 3; // NOTE: ZERO BASED. First page is nr. 0.
//You get this from the $_REQUEST (aka: GET or POST)
$result = $conn->prepare("SELECT *
FROM table
WHERE id= :id
LIMIT :pagesize
OFFSET :offset");
$result->bindValue(':id', $id);
$result->bindValue(':pagesize', $pagesize);
$result->bindValue(':offset', $pagesize * $pagenumber);
$result->execute();
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
This gives you the complete resultset of rows, limited to your required page. You need another query to calculate the total number of rows, of course.
What you could try is:
//Get your page number for example 2
$pagenum = 2;
//Calculate the offset
$offset = 7 * $pagenum;
//Create array
$data = array();
$result = $conn->prepare("SELECT * FROM table WHERE id= ? LIMIT 7 OFFSET ?");
$result->bind_param("ii", $id,$offset);
$result->execute();
$resultSet = $result->get_result();
while ($item = $resultSet->fetch_assoc())
{
$data[] = $item;
}
$result->close();
//echo resultSet you want
var_dump($data);

PHP: PDO fetch() returns nothing from database

When I use the following code, it returns nothing - no errors, no values. When I want to select just one specific row and display that data, using fetch() works fine. But the moment I put it in a loop to get multiple rows, nothing happens. Here is the code I am using:
$stmt = $pdo->prepare("SELECT name FROM company WHERE position = :position AND branch = :branch ORDER BY name ASC");
$position = 23;
$branch = "Management";
$stmt->bindParam(':position', $position, PDO::PARAM_INT);
$stmt->bindParam(':branch', $branch, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch()) {
echo $row['name'];
}

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