Not able to get the actual values from SQL result php - php

I am having some trouble getting some values from my sql query in php
This is my php code:
<?php
include "init.php";
$stmt = "SELECT email FROM Customer ";
$result = $dbcon -> prepare($stmt);
$result->execute();
$result->store_result();
while($result -> fetch()){
// This line below works
echo "Works";
// This doesn't work
echo $result['email'];
}
?>

You need to use bind_result() to retrieve the values returned by the query.
include "init.php";
$stmt = "SELECT email FROM Customer ";
$result = $dbcon -> prepare($stmt);
$result->execute();
$result->store_result();
$result->bind_result($email);
while($result -> fetch()){
// This line below works
echo "Works";
echo $email;
}

To start, mysqli::prepare doesn't return a mysqli_result, it returns a mysqli_stmt. You then have to execute that mysqli_stmt and either fetch directly from it into a bound variable, or extract a mysqli_result and fetch from that. There are several ways to do what you want:
$qry = "SELECT email FROM Customer ";
$stmt = $dbcon->prepare($qry);
$stmt->execute();
$stmt->bind_result($email); // Bind variable to statement
while($stmt->fetch()) // Iterate through statement
{
// This line below works
echo "Works";
echo $email;
}
Or:
$qry = "SELECT email FROM Customer ";
$stmt = $dbcon->prepare($qry);
$stmt->execute();
$rslt = $stmt->get_result(); // Retrieve result set
while($row = $rslt->fetch_assoc()) // Iterate through result
{
// This line below works
echo "Works";
echo $row['email'];
}
Or:
$qry = "SELECT email FROM Customer ";
$stmt = $dbcon->prepare($qry);
$stmt->execute();
$rslt = $stmt->get_result(); // Retrieve result
$resArray = $rslt->fetch_all(MYSQLI_ASSOC)); // Convert to array
foreach ($resArray as $row) // Iterate through array
{
// This line below works
echo "Works";
echo $row['email'];
}
As is my custom, I leave error handling as an exercise for the reader.

Related

PHP MYSQLI Query is failing

When trying to run a MYSQLI command in PHP, Its coming back failing.
function DB_query($query, $params = []) {
$conn = DB_connect();
if ($params)
{
$stmt = $conn->prepare($query);
$types = str_repeat('s', count($params));
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
} else {
$result = mysqli_query($conn, $query);
}
if ($result)
{
$result = mysqli_fetch_all($result);
return $result;
} else {
return mysqli_affected_rows($conn);
}
}
Here is my query:
DB_query("SELECT count(*) FROM members WHERE email = ? LIMIT 1",[$email])
It runs on:
$result = mysqli_fetch_all($result);
The results from $result: array(1)([0]=>array(1)([0]=>(int)1))
Here is my query:
DB_query("SELECT id, username, password FROM members WHERE email = ? LIMIT 1",[$email]);
It runs on:
$result = mysqli_fetch_all($result);
The results from $result: > array(0)
I have tried changing out the "mysqli_fetch_all" to fetch_all, but I cant figure it out. I need both query to run through the same function.
I cant figure out why the last query is returning nothing in the array.
<?php
$sql = "SELECT * FROM members WHERE email = '".$email."'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_row($result)) {
echo $row[0];
echo $row[1];
echo $row[2];
}
?>
Alternatively, you can use mysqli_fetch_array and use $row['fieldname'] inside the loop.

PHP - failed to output no data where no data in table

I've tried to find any reference to display data where no data in table for an hours, but I'm not yet found a code to fix the issue
I've this code:
//function
function readAll(){
$query = "SELECT * FROM ".$this->table_name." ORDER BY id_nilai ASC";
$stmt = $this->conn->prepare( $query );
$stmt->execute();
return $stmt;
}
//execute
$pro3 = new Nilai($db);
$stmt3 = $pro3->readAll();
while ($row3 = $stmt3->fetch(PDO::FETCH_ASSOC)){
// not yet fix how to display no data
//if($row3==false){ tried to change $row3==0 still won't work
//echo "No Data";
//}
//die(var_dump($row3)); showing `bool(false)`
echo $row3['ket_nilai'] (echo $row3['jum_nilai'])
}
any idea how to do?
I want to display some text when no data found in database table
You need to fetch the results before entering the loop, check if you do get the results then if you do enter the loop else display the message
see bellow code :
<?php
//function
function readAll(){
$query = "SELECT * FROM ".$this->table_name." ORDER BY id_nilai ASC";
$stmt = $this->conn->prepare( $query );
$stmt->execute();
return $stmt;
}
//execute
$pro3 = new Nilai($db);
$stmt3 = $pro3->readAll();
$results = $stmt3->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0){
foreach($results as $row3){
//display them
echo $row3['ket_nilai'] ;
echo $row3['jum_nilai'];
}
}else{
echo "No data available";
}
?>

Returning variables from a prepared statement function PHP

I have multiple pages on a website that require the same data from a table. So instead of writing out an sql statement on each page I want to write a function.
Here is my function:
function getInfo($u_id) {
global $conn;
$stmt = $conn->prepare("SELECT report.*, users.* FROM report INNER JOIN users ON report.report_user_id=users.user_id WHERE report_user_id = ? ORDER BY report_id DESC LIMIT 5") or die ('Problem Preparing Query');
$stmt->bind_param("i", $u_id);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
//reports
$report_user_id = $row['report_user_id'];
$rep_date = $row['rep_date'];
$rep_location = $row['rep_location'];
$rep_notes = $row['rep_notes'];
//users
$user_id = $row['user_id'];
$username = $row['username'];
$fname = $row['user_firstname'];
$lname = $row['user_lastname'];
$user_email = $row['user_email'];
$user_image = $row['user_image'];
$user_number = $row['user_number'];
}
$stmt->close();
}
The function works, in that it fetches the data from the table but I don't know how to output the variables. Any example I have seen using prepared statements in functions are for inserting data into a table rather than fetching data.
I have tried binding the results, creating an array, returning each variable but in every case I have errors or can only return the first variable.
The function as is does not throw up any errors on its own but further down my webpage when I try to use one of the fetched variables it tells me that it is undefined.
$u_id = 1;
getInfo($u_id);
<a class="text-inherit" href="profile/index.html"><?php echo $fname .' '. $lname; ?></a>
Notice: Undefined variable: fname in....
So my question is, how can I get the variables that have been fetched in this function?
Here is a single row result solution:
function getInfo($u_id){
global $conn;
$stmt = $conn->query("SELECT * FROM report INNER JOIN users ON report.report_user_id=users.user_id WHERE report.report_user_id=$u_id ORDER BY DESC LIMIT 1") || die ('Problem Preparing Query');
if($stmt->num_rows > 0){
return $stmt->fetch_object();
}
else{
// no results were found
}
return false;
}
$obj = getInfo($u_id);
if($obj){
echo "<a class='text-inherit' href='profile/index.html'>{$obj->user_firstname} {$obj->user_lastname}</a>";
}
function getInfo($u_id) {
global $conn;
$stmt = $conn->prepare("SELECT report.*, users.* FROM report INNER JOIN users ON report.report_user_id=users.user_id WHERE report_user_id = ? ORDER BY report_id DESC LIMIT 5") or die ('Problem Preparing Query');
$stmt->bind_param("i", $u_id);
$stmt->execute();
$rows = [];
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$stmt->close();
return $rows;
}
Of course it's not working since $fname and $lname are local variables in that function and when the function returns they are gone.
Put all of them inside an array and either return them or put them inside $GLOBAL.

mysqli_real_escape_string with mysqli_num_rows in php

My problem count sql .
<input name='d_n[]'>
<input name='d_n[]'>
php page
post value Adam's
foreach($ds_director as $key => $director){
// my problem here //
$DnumSql = "SELECT * FROM list WHERE ds_name = ?";
$stmt = $con -> prepare($DnumSql);
$stmt -> bind_param('s',$director);
$stmt -> execute();
$Dnum = $stmt->num_rows;
echo "$Dnum"; // result again '0'
/////////////
if($Dnum == 0){
$director_sql = mysqli_real_escape_string($con,ucwords($director));
$Dsql = "INSERT INTO movie_ds (ds_m_name, ds_name, ds_status) VALUES ('$director_sql', '$m_name', 'yönetmen')";
$Dquery = mysqli_query($con,$Dsql);
if($Dquery){
echo "<p style='color:green'>good</p>";
}else{
echo mysqli_error($con);
}
}else{
echo "<p style='color:red;'>not save</p>";
}
}
Because of this problem the same value is recorded
UPDATE PROBLEM editted = array input
Better to use prepare statement for this. It will automatically escape your string and prevent from sql injection
$sql = 'SELECT * FROM list WHERE d_n =?';
$stmt =$con->prepare($sql);
$stmt->bind_param('s', $_POST['d_n']);
$stmt->execute();
$numrows = $stmt->num_rows;

Returning an array with PDO - using FetchAll doesn't work

I use the following code to retrieve data from my database. The problem is that it only displays the first row. In this particular case, it means that only the first picture is shown on the webpage but I want to show all of them.
<?php
$sql = "SELECT `image-id`, `article-id`, `image-path`, `image-title` FROM `table-images` WHERE `article-id` = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":id", $id);
$stmt->execute();
if($result = $stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<a class="swipebox" href="<?php echo $result['image-path'];?>" title="<?php echo $result['image-title'];?>">
<img alt="image" src="<?php echo $result['image-path'];?>"></a>
<?php
}// end if
else {
echo '0 results';
}// end else
?>
I read this article so I tried to use the code:
if($result = $stmt->fetchAll(PDO::FETCH_ASSOC));?
... but that doesn't work. It doesn't even echo the first picture anymore. What am I missing here?
Here is how it works:
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":id", $id);
$success = $stmt->execute();
if($success){
//fetch here
}
Now you have 2 options for fetching the data:
fetch()
fetch() will get rows one by one so you need a while loop.
while($rows = $stmt->fetch(PDO::FETCH_ASSOC)){
// get data
}
fetchAll()
fetchAll() get all the rows at once so no need for loops to retrieve the data, but if you need to loop then you will need a for loop.
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
//do something
}
<?php
$sql = "Your SQL query";
$id = 1;
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":id", $id);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC)
if($stmt->rowCount()){
foreach($result as $row){
echo $row['row_name'].'<br/>';
}
}else{
echo 'No results found';
}

Categories