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
Related
I am new to OOP php and took some lessons and now Im trying to practice, I used login with discord method and If user Is logged in the system sould add the discord id to database if user is not already in database but Im facing quite the issue and I have no luck so far to fix It myself, I even asked few of my buddies If they can see the issue but they did not also know the real issue.
My error:
[22-Jul-2022 06:56:00 UTC] PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function
SignupContr::signupUser(), 0 passed in C:\wamp64\www\OOP-Test\inc\signup.inc.php on line 13
and exactly 1 expected in C:\wamp64\www\OOP-Test\classes\signup-contr.class.php:10
Stack trace:
#0 C:\wamp64\www\OOP-Test\inc\signup.inc.php(13): SignupContr->signupUser()
#1 C:\wamp64\www\OOP-Test\dashboard\index.php(12): include('C:\\wamp64\\www\\O...')
#2 {main}
thrown in C:\wamp64\www\OOP-Test\classes\signup-contr.class.php on line 10
My code looks like this right now:
signup.inc.php
{
$discord = $_GET['user'];
include "../classes/dbh.class.php";
include "../classes/signup.class.php";
include "../classes/signup-contr.class.php";
$signup = new SignupContr($discord);
$signup->signupUser();
//header('location: ../dashboard/index.php');
}
signup.class.php
class Signup extends Dbh {
protected function setUser($discord){
$stmt = $this->connect()->prepare("INSERT INTO `users` ('discord') VALUES (?);");
if(!$stmt->execute(array($discord))) {
// $stmt = null;
// header("location: ../dashboard/index.php?useraddfailed");
// exit();
}
$stmt->debugDumpParams();
$stmt = null;
}
}
signup-contr.class.php
class SignupContr extends Signup{
private $discord;
public function _construct($discord){
$this->discord = $discord;
}
public function signupUser(){
$this->setUser($this->discord);
var_dump($this->discord);
}
}
I have not done the check part If user Is allready In the database
I Finally found the issue. I was missing one underscore in construct.
signup.contr.class.php should be like this:
class SignupContr extends Signup{
private $discord;
public function __construct($discord){
$this->discord = $discord;
}
public function signupUser(){
$this->setUser($this->discord);
var_dump($this->discord);
}
}
Of course it was the simplest issue there Is but I really tought there suppost to be only one underscore. You always should check the simple things first, I did not because usally you don't use construct In procedural php
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
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.
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…