How can I collect result from prepare statement PHP? [duplicate] - php

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I can't collect the results of my query in this function :
<?php
function getBestScore()
{
require_once ('connection.php');
$idJoueur = session_id();
if ($stmt = $conn->prepare('SELECT bestScore FROM Player WHERE ID = ?'))
{
$stmt->bind_param('i', $idJoueur);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_assoc();
$bestScore = $data;
if (!(empty($bestScore)))
{
header("Location: ../index.php");
}
return $bestScore;
}
else
{
$error = $conn->errno . ' ' . $conn->error;
echo $error;
}
}
My connection works, I tried fetch_assoc(), store_result() but I failed every time.

If you want to select data then try the following
if ($stmt = $conn->prepare('SELECT bestScore FROM Player WHERE ID = ?')) {
$stmt->bind_param('i',$idJoueur);
$stmt->execute();
/* bind result variables */
$stmt->bind_result($result);
/* fetch value */
$stmt->fetch();
if (!(empty($result))) {
header("Location: ../index.php");
}
return $result;
}
Hope this helps.

Related

Mysqli error while callling second function in the same file [duplicate]

This question already has answers here:
error in calling same function twice in php
(2 answers)
Closed 2 years ago.
<?php
function insertData()
{
include_once 'database/connection.php';
echo "<br>============= Insert Data =================<br>";
try{
$sql = "INSERT INTO table1 (activity_date, activity_name, activity_point) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $activity_date, $activity_name, $activity_point);
// set parameters and execute
$activity_date = "06-APR-2020";
$activity_name = "Test";
$activity_point = "5";
$res = $stmt->execute();
var_dump("<br>Res:- ".$res);
print_r("<br>Result:- ".$res);
if ($res) {
echo "<br>Id:- ".$conn->insert_id;
echo "<br>New records created successfully";
}
else{
echo "<br>New records not inserted successfully";
}
}
catch(Exception $e){
echo "Exception:- ".$e;
}
finally{
$stmt->close();
$conn->close();
}
}
// insertData();
function selectData()
{
include_once 'database/connection.php';
echo "<br>============= Select Data =================<br>";
try{
$sql = "SELECT * FROM table1 WHERE activity_id > ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $activity_id);
// set parameters and execute
$activity_id = 6;
$stmt->execute();
if (!$stmt->errno) {
// Handle error here
}
$result = $stmt->get_result(); //
$rows = $result->num_rows;
if ($rows > 0){
while ($data = $result->fetch_all())
{
// var_dump($data);
var_export($data);
echo "<br>";
print_r($data);
}
}
else{
echo "Data Not Found";
}
}
catch(Exception $e){
echo "Exception:- ".$e;
}
finally{
$stmt->close();
$conn->close();
}
}
selectData();
?>
The insert function call correctly and data is also inserted correctly.
After inserting I am closing the connection in the finally block.
But at the same time calling selectData() function I got an error.
Undefined variable: conn and Undefined variable: stmt.
How should I reopen the connection for second function?
As you use include_once for your database connection inside the function, this will only load the script the first time. Also at the end of the function you close the connection...
$conn->close();
The second time it calls the function, the include is not done again and the connection is closed, so the connection is not re-made.
You should only create 1 connection for the entire script (rare exceptions may apply). So at the start of your script use the include and then pass the connection to any function/class which need to use it.
include_once 'database/connection.php';
insertData($conn);
Add the parameter to your functions...
function insertData( $conn )
and leave the closing of the connection to the system.
One last thing, which is more my preference is to use require_once or require rather than include_once or include as they will stop the script if the file cannot be found.

Fatal error: Call to a member function bind_param() on boolean [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 5 years ago.
I'm making a login script which fetches data from two tables. I understand that this error occurs when the statement returns FALSE AKA a boolean, but why is it returning false???
I made a function which works up to a point
function loginall($username, $password)
{
$db_host="localhost";
$db_username="root";
$db_password="";
$db_name="name";
$con=mysqli_connect($db_host, $db_username,$db_password, $db_name);
$mysqli = new mysqli("$db_host","$db_username","$db_password", "$db_name");
$qry = "SELECT username, password, level, active FROM businesses WHERE username=? AND password=?
UNION SELECT username, password, level, active FROM employees WHERE username=? AND password=?";
$stmt = $mysqli->prepare($qry);
$stmt->bind_param("ssss", $u,$p,$uu,$pp);
$u = $username;
$p = $password;
$uu = $username;
$pp = $password;
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
return $row;
}
}
it works great until I try fetching more columns from the tables, or even trying to SELECT * from the tables. I read through other similar questions and found codes to get the error to appear, but no luck. Thank you!
Your function will end/return as soon as it hits the first return statement in the loop (first iteration).
You will need to build the complete array and then return it once.
This ought to do it:
if(!($stmt=$mysqli->prepare($qry))){
return ["Prepare failed: ".mysqli_error($mysqli)]; // what does this say?
}elseif(!$stmt->bind_param("ssss",$u,$p,$uu,$pp)){
return ["Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error];
}else{
$u = $username;
$p = $password;
$uu = $username;
$pp = $password;
if (!$stmt->execute()){
return ["Execute failed: (" . $stmt->errno . ") " . $stmt->error];
}else{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$rows[]=$row;
}
return $rows;
}
}
Try backticking all of your column names. LEVEL is a MySQL KEYWORD.
Try this maybe bind_result() not get_result():
You might be wondering, why even use bind_result()?
This is strictly due to preference, as the syntax is considered to be more readable.
However, it should be noted that bind_result() may not be used with the * wildcard selector. It must contain explicit values
Here in this code using bind_result(), the values $usernameRow, $passwordRow, .... are form the database tebles:
.....
...
.
$stmt->bind_param("ssss", $username, $password, $username, $password);
$stmt->execute();
$stmt->store_result();
$numRows = $stmt->num_rows;
$stmt->bind_result($usernameRow, $passwordRow, $levelRow, $activeRow);
if($numRows > 0) {
while ($stmt->fetch()) {
$u[] = $usernameRow;
$p[] = $passwordRow;
$uu[] = $levelRow;
$pp[] = $activeRow;
}
}
$stmt->close();

check if row exists mysqli [duplicate]

This question already has answers here:
Commands out of sync; you can't run this command now
(23 answers)
Closed 8 years ago.
I am trying to check if row exists. I am getting
Commands out of sync; you can't run this command
I am getting this error because I added $stmt->store_result(); if I remove that line num_rows doesn't return true. How can I check if the row exists?
$title = urldecode($_GET['product-tit/']);
$id = $_GET['item-id-pr'];
$mydb = new mysqli('localhost', 'root', '', 'database');
if(empty($title) || empty($_GET['item-id-pr'])){
header('Location: products.php');
exit();
}
else{
$stmt = $mydb->prepare("SELECT * FROM products where title = ? AND id = ? limit 1 ");
$stmt->bind_param('ss', $title, $id);
$stmt->execute();
$stmt->store_result();
?>
<div>
<?php
if($stmt->num_rows < 1 ) {
echo "not found";
exit();
} else{
$result = $stmt->get_result();
echo $mydb->error;
while ($row = $result->fetch_assoc()) {
echo wordwrap($row['price'], 15, "<br />\n", true);
exit();
}
$mydb->close ();}}
?>
</div>
It's quite a strange desire of PHP users for the number of rows. Everyone is so eager to get it, while in a web-development there are only a few, extremely rare cases when one is really need it.
Say, here we actually need some data, not number of rows. But using this number only to see if we have any data. Doesn't it look funny/redundant? If we have our data already - why would we need any extra facilities to see if we have it or not?
<?
if(empty($_GET['product-tit']) || empty($_GET['item-id-pr'])){
header('Location: products.php');
exit();
}
$stmt = $mydb->prepare("SELECT * FROM products where title = ? AND id = ? limit 1 ");
$stmt->bind_param('ss', $_GET['product-tit'], $_GET['item-id-pr']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if (!$row) { // <---- HERE it is!
echo "not found";
exit();
}
?>
<div>

$stmt-num_rows ( Return 0 ) [duplicate]

This question already has an answer here:
$stmt->num_rows returning 0 even after calling store_result
(1 answer)
Closed 9 years ago.
i am just trying to learn prepared statement and i am following the PHP manual to guide me through, i have checked the answers regarding this problem on stackoverflow but, i can't find any solutions, the $stmt->num_rows always ( Return 0 )
there is a post on stackoverflow discussed the problem and they advised to use
$stmt->store_result() just before the $stmt-num_rows, but the $stmt->num_rows return 0
some one please can tell me what i am doing wrong here.... i am just sick of the procedural style coding and i want to enhance my skills with prepared statement
here is the function down below
function get_all()
{
// ** Initializing the Connection
$mysqli = Connect();
$sql = ( ' SELECT * FROM `users` ' );
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$res = $stmt->get_result();
echo $num_count = $stmt->num_rows();
$user = array();
for ($counter = 0; $row = $res->fetch_assoc(); $counter++)
{
$user[$counter] = $row;
}
return $user;
}
// This is the second update
function get_all()
{
// ** Initializing the Connection
$mysqli = Connect();
$sql = ( ' SELECT * FROM `users` ' );
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$res = $stmt->get_result();
echo $num_count = $stmt->num_rows;
$user = array();
while($row = $res->fetch_assoc())
{
$user[] = $row;
}
return $user;
}
// third update
function get_alll()
{
// ** Initializing the Connection
$mysqli = Connect();
// no need to use * character,
// need to write query this way
$sql = ( ' SELECT `id`,`fname`,`lname`,`uname`,`email` FROM `users` ' );
$stmt = $mysqli->prepare($sql);
// here need to use bind param
$stmt->bind_result( $id, $fname, $lname, $uname, $email);
$stmt->execute();
// it's important to store the result
// before using num rows
$res = $stmt->store_result();
echo $num_count = $stmt->num_rows;
//
while($stmt->fetch())
{
echo $fname;
}
}
num_rows is a property, not a method, try with $stmt->num_rows without brackets

Fetch a single row of data from mysqli prepared statement [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I have the following code and where if 1 row is found I would like to set the result to $aPrds, how can I do this?
$stmt = $db->prepare("select * from products where id=?");
$stmt->bind_param("s", $_GET['id']);
if($stmt->execute())
{
$stmt->store_result();
echo $stmt->num_rows;
if($stmt->num_rows==1)
{
//SET RETURNED ROW TO aPrds
}
else
{
echo "no results or too many found";
}
}
else
{
echo "sql invalid";
}
I have also tried the following code which has been unsuccessful (returns (null):
$stmt = $db->prepare("select productid, product_name, description from product where productid=?");
$a=1;
$stmt->bind_param("i", $a);
if($stmt->execute()){
$stmt->store_result();
if($stmt->num_rows==1){
$stmt->bind_result($b, $c, $d);
print_r($b);
print_r($c);
print_r($aPrds);
}else{
echo "no result or more than 1 returned";
}
}else{
echo "invalid sql";
}
Please note that I have tested the SQL and it works, also the $db mysqli connection is definitely working.
I think you are looking for the get_result and fetch_assoc methods:
// ....
$result = $stmt->get_result();
$aPrds = $result->fetch_assoc();
// ....
Edit:
Apparently these functions are not yet available (should have tested this, sorry). So this is tested:
function bind_array($stmt, &$row) {
$md = $stmt->result_metadata();
$params = array();
while($field = $md->fetch_field()) {
$params[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $params);
}
// ....
if($stmt->execute()) {
bind_array($stmt, $row);
$stmt->fetch();
print_r($row);
// ....
And you second solution should also work if you added $stmt->fetch() after $stmt->bind_result($b, $c, $d);

Categories