Call to a member function real_escape_string() on a non-object - php

I'm getting this error:
Call to a member function
real_escape_string() on a non-object
and here's $db
$db = new mysqli("127.0.0.1", "username", "password", "sch5400");
in code:
function readSession($sessionId) {
global $db;
$sessionId = session_id();
// escape session ID
$sessionId = $db->real_escape_string($sessionId);
$time = time();
$result = $db->query("SELECT sessiondata FROM sessions WHERE sessionid='$sessionId' AND expiry > $time");
if ($result->num_rows > 0) {
$row = $result->fetchRow();
return $row['sessiondata'];
}
// return empty string
return "";
}
It appears on line 5, relative to code above. Didn't I instantiate $db?

Probably the better solution would be to create a singleton function:
function get_my_db()
{
static $db;
if (!$db) {
$db = new mysqli("127.0.0.1", "username", "password", "sch5400");
}
return $db;
}
and use it like
$db = get_my_db();
in every function that needs db instance.

You haven't initialized $db anywhere in the code that's shown, and from the error it sounds like it hasn't been initialized anywhere else (yet) either.
If you are initializing $db somewhere, make sure it's before readSession is called. Also check for an error message when you make the connection. It returns false on error, which is not an object.
from the PHP manual, you should using one of these error checking methods to ensure the connection is established successfully:
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/*
* Use this instead of $connect_error if you need to ensure
* compatibility with PHP versions prior to 5.2.9 and 5.3.0.
*/
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}

There is also a global function that doesnt require a db reference.
$sessionId = mysql_real_escape_string($sessionId);
http://php.net/mysql_real_escape_string

Related

why mysqli_connect() returning true even I passing wrong username?

Here's my code.
<?php
$server = "localhost";
$uname = "replace it with anything";
$pswd = "";
$conn = mysqli_connect($server, $uname, $pswd);
if(!$conn){
die('Caught');
}
else{
die('Connected');
}
?>
No matter what I passed in the mysqli_connect() as username. It always returns true. In the case of the wrong password, it shows an error that accesses denied, but I don't know why, no matter what I enter in the username, it always returning true.
It does not return a boolean but an object which represents the connection. You can then check the object for connectivity. From the manual:
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
Try
<?php
$mysqli = new mysqli("host", "username", "password", "database") or die($mysqli->error());
if ($mysqli->connect_errno) {
echo "error";
exit();
}
?>

Fatal Error Call To a member Function query()

I've seen some of the previous posts on here but they really don't explain what it is I'm looking for. maybe someone can point me in the right direction.
All I'm doing is a simple select statement that works on some other pages but not this one.
at the top of my page, I have the connection to my db: include 'myDBconnection.php'; just like any other page that uses it.
I'm using these to tell me what errors I have:
ini_set('display_errors', 'On');
error_reporting(E_ALL);
and they are returning this:
"Fatal error: Call to a member function query() on a non-object in /var/www/vhosts/mydomainname.com/httpdocs/somedirectory/index.php on line 16"
So, this is my simple select statement that I'm trying to just display on the page:
<?php
//just a simple select statement
if($row = $con->query("SELECT * FROM ErrorCodeTable WHERE ErrorCodeID = 100"))//this is line 16 in my code
{
$eCodeId = $row['ErrorCodeID'];
$eCode = $row['ErrorCode'];
echo $eCodeId." = ".$eCode;
}
?>
So, I'm stumped. Why is it telling me that?
Just for clarity's sake, this is my DB connection and I'm reading from an INI file.
function getConnected()
{
$file = "../myConnection.ini";
if (!$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.');
$host = $settings['connection']['default_host'];
$user = $settings['connection']['default_user'];
$paass = $settings['connection']['default_pw'];
$dbName = $settings['connection']['default_db'];
$con = 'mysqli_connect("'.$host.'", "'.$user.'", "'.$paass.'", "'.$dbName.'")';
return $con;
}
//MYSQLI CONNECTION
$con = getConnected();
//CONNECTION CHECK
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
So, why do I get the "Fatal Error" message? Did I overlook or forget something in my query?
Be gentle. :-)
Remove the single quotes around the below statement
$con = 'mysqli_connect("'.$host.'", "'.$user.'", "'.$paass.'", "'.$dbName.'")';
^ ^
By enclosing it in single quotes , your $con behaves like a string instead of a connection resource. The mysqli_connect function will never be executed.
Simply rewrite it like..
$con = mysqli_connect($host,$user,$paass,$dbName);

Cloud SQL using mysqli error

I'm trying to output the results of a simple query using a Google Cloud SQL with a mysqli connection. I've properly set up a Cloud SQL instance and imported a SQL database. However, when I run my app, it seems to connect to the database - no errors are triggered there - but the logs show the following:
PHP Fatal error: Wrong SQL: SELECT * FROM students Error: No database selected in /base/data/home/apps/s~db-php-001/1.371796924944999585/main.php on line 18
Here's my code:
$conn = new mysqli(null,"root","",null,null,"/cloudsql/db-php-001:db-instance-001");
// check connection
if($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$sql='SELECT * FROM students';
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$rows_returned = $rs->num_rows;
}
Obviously, I'm triggering that error, but I'm can't figure out why. There is definitely a table named students in the database.
Anyone have any ideas?
Thanks!! Joe
You've set your database name to null. A connection is made like so:
$mysqli = new mysqli("localhost", "user", "password", "database");
The mysqli constructor can take in the following parameters (in this order):
$mysqli = mysqli($hostname, $username, $password, $database, $port, $socket);
In your case, you've set the parameters to be:
$hostname = null; //Defaults to mysqli.default_host
$username = "root";
$password = "";
$database = null; //Defaults to ""
$port = null; //Defaults to mysqli.default_port
$socket = "/cloudsql/db-php-001:db-instance-001";
To clarify, you can pass null for the database name. In the query you'd need to use the fully qualified table name (<database>.Students in your case). Or you can use the mysqli_select_db() function to select the database to use.

PHP and MYSQLI Error, Call to a member function query() on a non-object [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I'm getting the Call to a member function query() on a non-object when I try to call my function.
My code looks like this:
function add_profile() {
$hostname = "localhost";
$dbusername = "username";
$dbname = "dbname";
$dbpassword = "password";
$link = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
$sql = "INSERT INTO payment_profiles(id, client_id) VALUES ( '','$profile_id')";
$result = $mysqli->query($sql);
if (!result)
{
echo 'Error: ', $mysqli->error;
}
}
add_profile();
It says my error is on the line: $result = $mysqli->query($sql);
I'm assuming I'm not calling something properly. Thanks in advance for any help
In your code you're mixing both procedural and object-oriented code. Choose either one or the other. Here's how you would solve the problem the procedural way.
$result = mysqli_query($link, $sql, MYSQLI_USE_RESULT)
I'm getting the Call to a member function query() on a non-object when
I try to call my function.
That's because the $mysqli object is not declared anywhere (or is it)? Before you can use $mysqli you should first create an instance of mysqli and assign it to your object.
$mysqli = new mysqli("localhost", "my_user", "my_password", "database");
Only then you may call the methods of the mysqli class like $mysqli->query();
The error you made depends probably on two misconceptions:
1) you pasted half of your code from the procedural-style part of the mysqli manual and half from the oop part
2) you assume $mysqli is a global object instantiated with $mysqli_connect();. It is not. You should invoke the constructor with the new keyword if you'd like to use it as an object.
$link = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
/////
$result = $mysqli->query($sql);
///////

How to make mysqli connect function?

I'm having a problem with a function that connects me to the database using mysqli. What I'm aiming to have is to just type getConnected(); where I need the connection.
This is the code:
function getConnected()
{
$host = 'localhost';
$user = 'logintest';
$pass = 'logintest';
$db = 'vibo';
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
}
This is the error I get when I try to use $mysqli after calling getConnected():
Notice: Undefined variable: mysqli in C:\xampp\htdocs\xampp\loginsystem\index.php on line 19
As some users have suggested (and is the best way), return the mysqli instance
function getConnected($host,$user,$pass,$db) {
$mysqli = new mysqli($host, $user, $pass, $db);
if($mysqli->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
return $mysqli;
}
Example:
$mysqli = getConnected('localhost','user','password','database');
You don't need to create such function. The connection to mysqli is only 3 lines of code when done properly. Definition and execution of such function would add twice as much.
Remember to always follow the three steps when opening a connection:
Enable mysqli error reporting.
Create instance of mysqli class.
Set the proper charset. Recommended one is utf8mb4
If you would like to have these 3 lines wrapped in a function you could do something like this:
function getConnected(): \mysqli {
$host = 'localhost';
$user = 'logintest';
$pass = 'logintest';
$db = 'vibo';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli($host, $user, $pass, $db);
$mysqli->set_charset('utf8mb4');
// return the instance of mysqli class
return $mysqli;
}
However, hardcoding the values does not make much sense. The values should be coming either from environment variables (e.g. read using getenv() function) or from config file. For example:
function getConnected(): \mysqli {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli(getenv('DB_HOST'), getenv('DB_USER'), getenv('DB_PASS'), getenv('DB_NAME'));
$mysqli->set_charset('utf8mb4');
// return the instance of mysqli class
return $mysqli;
}

Categories