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 am working on a project where I have a DB_Functions.php file to store all needed PHP functions.
Here is one of them:
public function getUserByEmailAndPassword($email, $password) {
$stmt = $this->conn->prepare("SELECT id, email, encrypted_password, salt,imagen,nombre,apellidos,created_at,unique_id,nivel_usuario,verified,cel_verificado,tel FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
$stmt-> bind_result($token1,$token3,$token4,$token5,$token6,$token7,$token8,$token9, $token10,$token11,$token12,$token13,$token14);
while ( $stmt-> fetch() ) {
$user["id"] = $token1;
$user["email"] = $token3;
$user["encrypted_password"] = $token4;
$user["salt"] = $token5;
$user["imagen"] = $token6;
$user["nombre"] = $token7;
$user["apellidos"] = $token8;
$user["created_at"] = $token9;
$user["unique_id"] = $token10;
$user["nivel_usuario"] = $token11;
$user["verified"] = $token12;
$user["cel_verificado"] = $token13;
$user["tel"] = $token14;
}
// verifying user password
$encrypted_password = $user['encrypted_password'];
// check for password equality
if (password_verify($password, $encrypted_password)) {
// user authentication details are correct
return $user;
}
} else {
return NULL;
}
}
I am using the same file DB_Functions.php on two different servers.
Server 1 is a hosted web server with PHP 7.4 (ea-php74).
Server 2 is a AWS Ubuntu instance with PHP 7.4.11 (Zend).
On server 1 I am not getting any error using above mentioned function.
On server 2 I am getting following error:
PHP Fatal error: Uncaught Error: Call to a member function bind_param() on bool in /var/www/html/android_api/include/DB_Functions.php:1942\nStack trace:\n#0 /var/www/html/android_api/login.php(17): DB_Functions->getUserByEmailAndPassword()\n#1 {main}\n thrown in /var/www/html/android_api/include/DB_Functions.php on line 1942
What should I do to get the function working on server 2?
Have a look to what does method mysqli::prepare return https://www.php.net/manual/fr/mysqli.prepare.php
"mysqli_prepare() returns a statement object or FALSE if an error occurred."
Error says that $smtp is a bool and you are trying to use bind_param method on a bool. Have a look to the last $smtp assignation. Regarding what does the prepare method can return, it look like the method returned false. So there were an error while trying to prepare the statement.
Related
I booted up wamp today to check something for one of my website and ran across a php error
[30-Jan-2022 16:57:28 UTC] PHP Fatal error: Uncaught Error: Call to a member function prepare() on boolean in C:\wamp64\www\includes\class.database.php:130
Stack trace:
When checking the php file in question i have no idea how to fix this, anyone that can help?
// Allow for prepared arguments. Example:
// query("SELECT * FROM table WHERE id = :id", array('id' => $some_val));
$sth = $this->db->prepare($sql);
$debugSql = $sql;
$params = array();
if (is_array($args_to_prepare))
{
foreach ($args_to_prepare AS $name => $val)
{
$params[':' . $name] = $val;
$debugSql = preg_replace('/:'.$name.'/',"'".$val."'", $debugSql);
}
}
The best way to reuse functions is to put it inside of the include file, then include it at the top of each file you'll need it. So inside of your db_connection.php, create your function:
Click this
I already tried other solutions from similar questions but it seems that nothing worked. Like the title says, the query I need to execute on my db works fine on phpMyAdmin, but it doesn't work when used inside a php function. This is the code in common_functions.php:
function eliminaRistorante($id_ristorante) {
global $conn;
// query su ristorante
$sql = "DELETE FROM ristorante WHERE id_ristorante = $id_ristorante";
echo $sql;
if($conn->query($sql) === TRUE) {
return true;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
return false;
}
}
This is the code in hold.php:
include('includes/logic/common_functions.php');
if (isset($_POST['del'])) {
$id_ristorante = $_POST['del'];
eliminaRistorante($id_ristorante);
header('location: admin/ristorante.php');
}
I put an echo statement to see if the query was effectively correct.
This is the output:
DELETE FROM ristorante WHERE id_ristorante = 5
Fatal error: Uncaught Error: Call to a member function query() on null in C:\xampp\htdocs\projects\db_ristorante\includes\logic\common_functions.php:57 Stack trace: #0 C:\xampp\htdocs\projects\db_ristorante\hold.php(8): eliminaRistorante('5') #1 {main} thrown in C:\xampp\htdocs\projects\db_ristorante\includes\logic\common_functions.php on line 57
Lastly, I tried these solutions:
MySql query not in working in PHP but works in phpMyAdmin
Inside that question the user kindly shared other solutions that I considered too.
Uncaught Error: Call to a member function query() on null in
your $conn Object is null. You did not initialise a PDO instance.
Here is a introduction, on how to do that, PHP The Right Way - PDO
So I am new to the OOP concept. I decided to make a call to my database, but in OO way. The error I am getting is:
Trying to get property 'num_rows' of non-object (at line 83 *reference to line 83)
I understand the error message, but fail to find out what is wrong regarding it. I have tried the following links, but unfortunately none of them have helped me really further, or I failed to understand what they meant.
Notice: Trying to get property 'num_rows' of non-object in line 35
Error - Trying to get property 'num_rows' of non-object
Get property num_rows of non-object
Trying to get property 'num_rows' of non-object
This is the reason I am knowingly making a duplicate question, hoping my problem would be something that has not (yet) been addressed in the other posts.
require 'connection.php';
//class DatabaseQueries handles all the queries required regarding CRUD.
class DatabaseQueries
{
//the SQL string
private $sql;
// The connection -> completegallery
private $conn;
public function __construct($conn)
{
$this->conn = $conn;
}
// function will check whether email already exists or not.
protected function getEmailExistance(string $email)
{
//create the SQL
$this->sql = $this->conn->prepare("SELECT * FROM userinfo WHERE email = ?");
//bind the parameter to it (preventing sql injection this way)
$this->sql->bind_param('s', $email);
// $result = the execution of the SQL.
$result = $this->sql->execute();
$resultCheck = $result->num_rows; //* line 83
var_dump($result); // returns boolean true.
var_dump($this->sql); // returns a mysqli stmt object
//check whether $resultCheck > 0
//if yes, that would mean the userName already exists.
if (!empty($result) && $resultCheck > 0)
{
exit('should show something');
} else
{
exit('always fails here');
}
}
} // ending class DatabaseQueries
How I call the class DatabaseQueries:
class Base extends DatabaseQueries
{
private $email;
private $userName;
private $name;
private $lastName;
private $pwd;
private $pwdConfirm;
// here is the code where I check and assign the user input to the variable $email etc.
//this method is for test purposes only and will be removed after the website is 'done'.
public function getEverything()
{
//link to check whether email is being used or not
$this->getEmailExistance($this->email);
}
}
How I invoke the objects etc.
$userInformation = new base($conn);
$userInformation->setEmail($_POST['registerEmail']);
//some other info, but not relevant to the problem.
I have already checked whether I misspelled anything, but this wasn't the case. The connection in connection.php has been declared correct aswell.
As mentioned in the comments, execute() does not return the result, you have to fetch() it. Here is the code that should allow you to do what you are asking.
// function will check whether email already exists or not.
protected function getEmailExistance(string $email)
{
//create the SQL
$this->sql = $this->conn->prepare("SELECT * FROM userinfo WHERE email = ?");
//bind the parameter to it (preventing sql injection this way)
$this->sql->bind_param('s', $email);
// $result = the execution of the SQL.
$this->sql->execute(); <---- No need for variable here, its boolean
$result = $this->sql->store_result(); <---- The result
$num_rows = $this->sql->num_rows; <---- This will contain your row count
if (!empty($result))
{
// fetch your results here
} else
{
exit('always fails here');
}
}
I am getting an error code and I really can't tell what the problem is here:
public static function createRecord($mysql, $id, $username) {
$login = new login;
$delete_from_sessions = $mysql->prepare("DELETE FROM com_sessions WHERE uid = ?");
if(!$delete_from_sessions) {
printf("Some error occured: %s\n", $mysql->error);
} else {
$delete_from_sessions->bind_param('s', $id);
$delete_from_sessions->execute();
}
// CALL FUNCTIONS IN CLASS login
$token = $login->createString(64);
$serial = $login->createString(64);
$login->createCookie($id, $username, $token, $serial);
$login->createSession($id, $username, $token, $serial);
$create_session = $mysql->prepare("INSERT INTO com_sessions (uid,token,serial,timestamp) VALUES (?,?,?,?)");
$create_session->bind_param('ssss', $id, $token, $serial, $posted_on);
$create_session->execute();
}
So what basically is happening here is, that whenever a user fills out the login-form at index.php and their userdata is correct, the function createRecord gets called and the variables from the index's inputs are passed as arguments $id for the user's id (gotten through a query within the login-script) and $username obvously as the user's name. The query is giving me the error:
Some error occured: Commands out of sync; you can't run this command now
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in C:\xampp\htdocs\session\new.session.php:101 Stack trace: #0 C:\xampp\htdocs\index.php(28): login::createRecord(Object(mysqli), 11, 'Kevin') #1 {main} thrown in C:\xampp\htdocs\session\new.session.php on line 101
I've tried to take out the query and just let the functions below fire off and those ironically worked, so the variables are passed over correctly. The table name and the database connection are both correct, I've checked that multiple times. Also I've tried to free the results of my connection through $mysql->free();.
I truly need your help. I have seen answers and even followed advice as previously posted but NO SOLUTIONS SHOW how to use fetch associated array using PREPARED STATEMENTS so I am not trying to submit an already answered question. I have followed suggestions to others questions but I am still getting:
Fatal error: Call to a member function fetch_assoc() on a non-object in /xxx/xxxxxx.php on line 75
I am showing you the old code using MySQL and how I have changed it to MySQLi using prepared statements, but I am still getting the same Fatal Error. Can someone please help me, I am going crazy and I truly need to find out what I am doing wrong. Thanks for your help.
//*******************************************************************
// OLD CODE:
// Called by: $theme=$log->get_theme();
//*******************************************************************
class redirect
{
function __construct()
{
}
function get_theme()
{
$rs=mysql_query("select * from theme where status='yes'");
if(mysql_num_rows($rs)>0)
{
$data=mysql_fetch_array($rs);
return $data['theme_name'];
}
}
}
//*********************************************************************
// OLD CODE:
// Called by: $theme=$log->get_theme($cn);
//*********************************************************************
class redirect
{
public $cn;
function __construct()
{
}
function get_theme($cn)
{
$themeStatus = 'yes';
if ($stmt = $cn->prepare("SELECT * FROM theme WHERE status = ? "))
{
$stmt->bind_param("s", $themeStatus);
$result = $stmt->execute();
$stmt->store_result();
if ($stmt->num_rows >= "1")
{
$data = $result->fetch_assoc(); // ERROR LINE
return $data['theme_name'];
}
}
else
{
echo "Failed to execute prepared statement: " . mysqli_connect_error();
}
}
}
The mysqli_stmt::execute method returns only bool by definition. So calling $result->any_method_name() will fail because $result is a boolean value.
To get the values from a prepared statement using the MySQLi library you bind your target variables with $stmt->bind_result(...) and then use $stmt->fetch() in a while loop to get the result of your query in your bound variables. And after that you switch from MySQLi to PDO because it has a better API regarding this…