mysqli_connect() causes fatal error - PHP - php

I have the following lines of code in a script;
include '../details.php';
$conn = false;
//$conn = mysqli_connect($servername, $username, $serverpassword, $dbname);
if(!$conn){
echo "no connection";
//header("location: //www.mattwoolford.co.uk/contact/?err=003");
}
The commenting out and $conn = false; is for debugging, as is the echo statement. Here's the deal:
When I uncomment $conn = mysqli_connect(), the page goes blank from an error. Tried or die() to no avail. Tested echoing the credentials from details.php, and they present themselves correctly and successfully.
What's happening and why?
UPDATE:
Error is shown to occur on a following line:
$service = mysqli_real_escape_string($conn, $service);
"Catchable fatal error: Object of class mysqli could not be converted to string in ("path") on line 81"
UPDATE 2: FIXED
An EOT; was indented, so it was trying to convert all the functions respectively as if it were included within <<<EOT
EOT;

There may be multiple things happen:
Confirm the file path, may be it's not getting the actual file path.
Try to connect with mysql connection setting, May server support earlier mysql version.
Final thing, check for the dbname, username, password and host url.
So there can be only these three possibility, Try to do it.
It should fix.
Thanks

Related

Strange inconsistency, database connection from require_once not working in only one place

I've encapsulated my MySQLi connection logic in a script named connect_mysqli.php. This working just fine all over my project (9 other pages are having no trouble), but one page is returning this error:
Warning: mysqli::query(): Couldn't fetch mysqli in C:\xampp\htdocs\projectName\php_calls\AddItem.php on line 193
Here's the code that's not working in AddItem.php:
$sql = <<<HEREDOC
UPDATE listing_data
SET ebay_id = '$responseObj->ItemID'
WHERE listing_id = '$database_listing_id'
HEREDOC;
require_once(__DIR__ . '/connect_mysqli.php'); //this creates $conn
$conn->query($sql); //this is line 193
And this is the code from connect_mysqli.php:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$db = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->set_charset("utf8");
Again, this is working without trouble in every other spot in the project. Here's what I've tried so far:
I checked my SQL syntax. I echoed the SQL query I'm attempting and tested it on the command line, the query is working fine.
Double check my SQL again. I copied the code from a working database call into the AddItem.php. It produces the same error. I tested the original page where this code exists, it works correctly in that spot.
I checked to make sure require_once is working correctly. To make sure my relative path was working correctly, and I am in the cwd that I expected I was in:
echo require_once(__DIR__ . '/connect_mysqli.php');
and it produced:
C:\xampp\htdocs\projectName\php_calls/connect_mysqli.php
This was expected. I opened Windows Power Shell and ran:
cat C:\xampp\htdocs\projectName\php_calls/connect_mysqli.php
This displays the code inside connect_mysqli.php! I was beginning to guess my require_once was flawed.
Check to see if there's a naming collision.
var_dump(get_defined_vars());
There is only one $conn.
The connection is not being closed with $conn->close();. If it's closing without my instruction I don't know how or why.
I copied and pasted the code from connect_mysqli.php into AddItem.php and the error goes away. So somehow my require_once must be messing up my connection. AddItem.php and connect_mysqli.php are in the same folder. I tried connecting with this line instead:
require_once('connect_mysqli.php');
I still get an error.
Sorry for the incredibly lengthy question, I wanted to do my research and try everything before creating another question on the topic. For now I can copy the database connection code into AddItem as a workaround, but it's bad practice, and there's clearly some important principle escaping me here that I'd like to understand.
Edit: more information
Nico Haase asked the question that put me on the right track. Line 1 of AddItem.php is a require_once:
require_once(__DIR__ . '\return_item_php_obj_by_id.php');
and inside return_item_php_obj_by_id.php we have the culprit:
require_once(__DIR__ . '/connect_mysqli.php');
//edited out irrelevant code
mysqli_close($conn);
In the original post I said "There's no $conn->close() hiding anywhere." Clearly I was mistaken. I found the hidden close(). When I comment this out, the connection works. Now I've accidentally made my code really hard to read, and I don't want to use a database connection that far away on the stack. Should I leave the connection open so I can use it again with AddItem.php? What's best practice in this case?

Build database if mysqli return error constant 'ER_BAD_DB_ERROR'

Hey guys I want to be able to run queries to build up my database if mysqli returns error constant of 'ER_BAD_DB_ERROR'/1049. Here is my code. If the error is caught I don't want mysqli to display the error but rather just built the database.
What happens it that the unknown database error is display, error is caught in the if() statement and the database is built.
I realize mysqli if displaying the error because of this:
$connection = mysqli_connect($db_server, $db_user, $db_pwd, $dbname);
How do I just build the database in place of displaying the error if that exact error that I want is caught.
$db_server = "localhost";
$db_user = "user";
$db_pwd = "";
$dbname = "name";
#connect to database
$connection = mysqli_connect($db_server, $db_user, $db_pwd, $dbname);
#try to catch database not exist error
if ('ER_BAD_DB_ERROR') {
# if true build database and connect again
build_db();
$connection = mysqli_connect($db_server, $db_user, $db_pwd, $dbname);
} else {
#close connection with other errors encounter
die("database connection failed". mysqli_connect_error());
}
I'm not sure if I'm following best practices here. So, I'm wholeheartedly open to suggestions and feedback. Thanks Guys.
You are looking for
mysqli::$connect_errno — Returns the error code from last connect call
Example:
$link = mysqli_connect('localhost', 'user', 'password', 'my_db');
// check if the connect call returned a database object
if (!$link) {
// check the particular error number why the connect failed
if (mysqli_connect_errno() === ER_BAD_DB_ERROR) {
// the database does not exist, so build it now
build_db();
} else {
// something else caused the connect to fail
}
}
This assumes the constant ER_BAD_DB_ERROR exists. I haven't checked if it does. If it doesn't exist, you will need to define it with a value corresponding to the correct error code returned by mysqli_connect_errno.
You can also use mysqli_connect_error() to get a textual representation of the error and compare that instead of just the error code.
Quoting the PHP Manual on where to find the error codes:
Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.
Note that this will still display a message about the missing database. You can either introduce a custom error handler for this particular error or just put an error suppression operator in front of the mysqli_connect call, e.g. change it to #mysqli_connect.

Why does my mysqli_query return false?

I realise there are a lot of questions like this here, but none of them seem to help me. The problem is as follows:
I have a website with an SQL Database, and now I am developing an application that reads the data. I've read that the best way to do that is a web service, so I'm in the process of writing one now. First, I'm trying to get all the data to display on a webpage, for testing purposes. I have the following code now:
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$db = "mydatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $db, 3306);
// Check connection
if (!$conn){echo "Not connected";} else {echo "connected";}
$query = "SHOW TABLES FROM mydata";
$result = mysqli_query($query) or die(" but not executed" . mysqli_error());
?>
When I save this and go to mywebsite/test.php, it displays the following:
connected but not executed. That means that it connects right, but the mysqli_query() returns false. However, mysqli_error is empty.
This is the entire test.php file. Am I missing something?
"Am I missing something?"
Yes, db connection arguments to both mysqli_query() and mysqli_error().
RTM's
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.error.php
It's all in there.
Btw, this is a community wiki. No rep should come of this.
If that still doesn't work, then you may have to remove the port , 3306.
Your $query appears to say
SHOW TABLES FROM mydata
However, your database is actually called mydatabase, as demonstrated on the $db line.

Message not getting printed on the browser in php?

Here is my code in php:
<?php echo "hello world";
$con = mysql_connect("localhost","root","root123");
echo "Connected";
mysql_close($con);
echo "hell"; ?>
Its printing hello world ,connected ,hell in terminal but it only prints hello world when i run it in the browser. Can anyone tell me why is this happening?
Thanks.
May be there has occurred an error in server side and server is not showing informatin about error. You look at error.log.
Please dont use mysql_*, use mysqli_* instead.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "collectively-codeigniter";
echo "hello world";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo "Not Connected";
} else {
echo "Connected";
}
// Close connection
$conn->close();
echo "hell";
?>
I do not see syntax errors and since you said that echo() functions before the connection line work, I guess the problem could be the connection:
Replace mysql_connect with mysqli_connect and mysql_close with mysqli_close because mysql_* is now deprecated.
Add the following code after the connection line:
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
This will check if the connection succeeded and if it failed it will print the error description.
Other things that could cause the problem are:
You do not have MySQL modules installed
MySQL service is not running (to check windows services: run -> services.msc)
Let me know if this helped you :)
You are obviously running into an error server side before the output has a chance to take place. Possibly it's when you try and connect to the mysql server that everything goes south. That results in an error that you have configured PHP not to show (very good for production, not so good when developing), thus you see "nothing".
Start by enabling error reporting in PHP via the php config file or setting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
at the top of your script. That should give you a clearer picture of what you issue actually is. A guess would be that you are unable to connect to the mysql server due to privileges on the mysql server, the port used, credentials or something of that nature.
Also, as stated, depending on the version of PHP you are running mysql_* command are deprecated and you should instead use the mysqli_* functions, PDO or something like that.

Access denied for user 'www-data'#'localhost - how to deal with that?

I face with a strange problem yesterday. I have server running Debian with installed PHP 4.4.4-8 and mysql 5.5.9. That server serves a several websites.
For some reason randomly I get that error "Access denied for user 'www-data'#'localhost' (using password: NO)" when I try to load the webpage.
If I hit refresh the page loads normally, but afer several clicks that message appears again. Username which that page use to connect to mysql server is not www-data.
Does anyone has faced similar problem ?
www-data is the Debian user that runs apache and php. If you attempt a query when you don't have a valid connection, php/mysql will attempt to create a connection using <unix-user>#localhost with no password. This is where www-data#localhost (using password:NO) is coming from.
The most likely reason that this has started happening now (though it has been running fine for 2-years prior) is that your db load has increased to the point where some connections are unable to succeed (probably due to max_connections, or max_user_connections; though this can also result from other limits like memory, threads, etc). When this happens, your call to mysql_connect will emit an error message, and return FALSE. If you fail to detect this failure, then your next mysql call (probably mysql_query, or mysql_select_db) will attempt the connection to www-data#localhost -- thus causing the problem you're seeing.
I suggest enabling error reporting, and error display (as suggested by #DarkMantis) :
ini_set('error_reporting', E_ALL|E_STRICT);
ini_set('display_errors', 1);
Also, be sure that your call to mysql_connect is not preceded by a # sign; and make sure to check the return value. It should look something like this:
$cxn = mysql_connect('localhost','yourusername','yourpassword');
if( $cxn === FALSE ) { die('mysql connection error: '.mysql_error()); }
It sounds like the query that is causing the error happens when something specific is called. This could mean that when the query is called, you aren't connected to the database with the correct username/password.
Try to ensure that you are definatly connected, use or die(mysql_error()); at the end of all your query variables to debug them.
Also, use the following two lines at the top of your php file:
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
That will show you any little php errors that may occur within your class/file which you may not have picked up before.
If your still having a problem after this, please post your PHP code and I will take a look at it directly.
Thanks!
i faced the same problem.
The problem was in my config.php!
I simply changed the $dbserver from
"127.0.0.1" -> "localhost".
Now the connection works again!
For absent-minded people, this error may happen when mysql_query() is called after mysqli_connect(), when it should be mysqli_query().
Use password 'NO'
(MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Deactivating safe mode fixed it for me:
Notice: mysql_connect(): SQL safe mode in effect - ignoring host/user/password information in /var/www/html/test.php on line 4
For solve this problem. I had to change the connection script Using
(MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Categories