PHP mysqli acting really screwy - php

I am attempting to use PHP to connect to a database for the first time. I found an online tutorial that was teaching me how to use mysqli to do this. It talked about mysqli_connect($host, $name, $pass, $db) and that worked just fine. The problem was when the tutorial asked me to check for errors using the function mysqli_connect_errno() because apparently whatever version of PHP I am running doesn't recognize that function. But according to the internets, im the only weirdo who's copy of PHP is having this issue. Why can't my PHP recgonize mysqli_connect_errno()? (Note: I am running wampserver on a Windows 8.1 desktop and PHP version is 5.5.12) (UPDATE: the actual username is supossed to be "web")
Here is my PHP Code:
<?php
$sql = mysqli_connect("localhost", "sweb", "nsjk99", "Inventory");
if( mysqli_connect_errno() ) {
die("Database connection failed: " . mysqli_connect_error() . "( " . mysqli_connect_errorno() . ")");
} else {
echo "<p>Your connection was a success</p>";
}
?>
Result:

The function is called mysqli_connect_errno() and not mysqli_connect_errorno(), as you have on line 4.
Edit
You don't need to pass the connection link as a parameter as stated in the manual.
The function catches the error number from the last call to mysqli_connect().
Thanks to David Rosa for the warning.

Related

Can't connect to database with php? [duplicate]

This question already has answers here:
How to make mysqli connect function?
(2 answers)
Closed 5 years ago.
I'm trying to connect to my database via php but I keep getting a 500 Internal Server Error. It is hosted on GoDaddy. I'm fairly new to php. Here is my code:
<?php
// Create connection
$conn = mysql_connect('server name', 'username', 'password');
mysql_select_db('users', $conn);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
?>
Obviously I have entered my server name, username and password but not showing them here. I can't get it to connect at all. I wanted to be able to just to display a row of data on a page to check it works but I can't even get that far yet! I'm probably missing something obvious. Any help would be great. Thanks!
There are several reasons for getting 500 error on page and will discuss all of them below.
You have used mysql_* function to establish connection to database which is deprecated in newer version of php.
You may have issue with .htaccess code which is blocking you.
However you can check some points to figure out your issue.
Check your .htaccess file whether it is blocking you or not
Check your php version (If you php version is >= 5.5) then try below.
<?php
// Create connection
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
Hope this will help you!!
Thanks & Regards
you seems to be use the mysql as an object and it is not supported only mysqli that can behave like this .
so if you need to use mysql extension and it is not recommend since it is deprecated.
<?php
// Create connection
$conn = mysql_connect('server name', 'username', 'password');
mysql_select_db('users', $conn);
// Check connection
if (!$conn) {
die("Connection failed: " . mysql_error());
} else {
echo "Connected successfully";
}
?>

How to detect MySQLi initialization error

In my website I am initializing DB connection using values read from config file, like this:
$this->mysqli = new mysqli($databaseInfo->MySQL_Host, $databaseInfo->MySQL_User, $databaseInfo->MySQL_Pass, $databaseInfo->MySQL_Db);
(for the record, values are being read from file properly and when everything is OK, db connection works just fine)
then I ask whether an error occurred during creating MySQLi object:
if (($this->mysqli!=null)&&($this->mysqli->errno == 0)) {
if no, then I want to set an error variable and handle it later in the code...I want this check only passes when no problem occurred...I thought "errno" variable provides sufficient check...
but apparently not, because regardless any error, I produce in config file, the code still jumps into "everything is fine" branch...obviously PHP produce a lot of warnings and finally it crashes on some fatal error related to the fact database doesn't work as expected
so my question is - how to set up this DB connection initial check properly to avoid such situation?
From PHP Manual, try this:
if (!$mysqli->error) {
printf("Errormessage: %s\n", $mysqli->error);
}
If using PHP OOP
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
?>
If using procedural style PHP
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
?>

Can't connect to database "Fatal error: Call to undefind function mysqli_connect()"

I've been scouring this site for 5 hours now trying to get this sorted, I rarely ask for help but this is one of the weirdest and most annoying things I've encountered.
First of all I'd like to say that this DID work fine, I have limited examples of what the cause is but I'll list them anyway.
Here's the full error message:
Fatal error: Call to undefind function mysqli_connect() in C:\wamp\www\game\connect.php on line 3
And here's the code
<?php
// Create connection
$con=mysqli_connect("localhost","root","","game");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$select_db = mysqli_select_db($con, 'game');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
?>
Weird thing is, it was working completely fine and just suddenly stopped, this has happened more than once.
Here's what I've tried:
Checking the extensions are enabled -
Rebooting various times -
Setting the correct php path -
Using many example codes that "work" -
I also had some code that inputted data straight from phpdesigner into the database, which successfully worked, but that no longer works and I've made literally 0 changes.
The last time it stopped working, I filled out a registration form on my site as a test (that doesn't work either) and it suddenly went off. When filling in the form I click register and nothing happens besides a refresh.
Bit extra: In my httpd file the pfp and pfpinidir are as follows
php5_module"c:/wamp/bin/php/php5.5.12/php5apache2_4.dll"
PHPIniDir "C:\wamp\bin\apache\apache2.4.9\bin\php.ini"
Your mysqli extension might not be enabled. so u need to enable that.
You have two PHP binaries on your machine. One is connected to the Apache, and is the one u use when you surf to a web page.
The phpinfo() shows you which php.ini file is used by the web php binary. u need to edit this file and in it activate the mysqli extension
You're trying to connect to DB twice, plus you're mixing MySQL APIs with mysql_error(), they do not mix together.
The 4th parameter is the DB name which is what you've done in the first example.
Use either:
<?php
// Create connection
$con=mysqli_connect("localhost","root","","game");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
or omit ,"game" from mysqli_connect() - while mysqli_error() requires DB connection parameter.
<?php
// Create connection
$con=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$select_db = mysqli_select_db($con, 'game');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($con));
}
?>

The mysqli_connect not working

I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.
$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');
Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?
My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?
Looks like MySQLi extension is not installed. What does var_dump(function_exists('mysqli_connect')); output?
Do you have error_reporting(E_ALL); And ini_set('display_errors',1); ?
The problem could be somewhere else.
Also how do you know it's failing if it is not priting the message in Die()?
for the host, if you are using "localhost:8889",
try using "localhost", and in the mysqli_connect() put in '8889' (or whatever port you are using) as an argument after the other arguements.
worked for me.
eg:
mysqli_connect('localhost','root','root','dbname','8889');
If you pass no values, I think MySQL is using defaults from the settings ini. So maybe this happens too if you pass empty values. In that case the connection could actually be established, and the result won't 'die'. Best thing is to use var_dump to check what $dbc contains after the call and continue from there.
But anyway, there is no way, PHP is going to tell you which settings to use if you don't remember them. :)
If you just installed mysql, then there exists only the root user, without a password (or blank one if you prefer). You are strongly encouraged to change that password AND create a new user and password for your application, who has only access to just one database, the one your application uses.
To change the root password, you may do this:
$ mysql -u root -p
Enter password: [press enter]
mysql> use mysql;
mysql> UPDATE user SET `password`=PASSWORD('your_desired_password') WHERE username='root';
# this next bit is to create a database and a username for your web application
mysql> CREATE DATABASE your_application_name;
mysql> GRANT ALL ON your_application_name.* TO 'your_username'#'localhost' IDENTIFIED BY 'yourpassword';
Obviously change all your_* values with correct ones.
For the reason why the die() gets not executed, do what #yes123 and #binaryLV had said (I think both are right, the mysqli is not installed, so it throws a E_FATAL_ERROR upon calling mysqli_connect(...) and as error_reporting is disabled (or maybe display_errors, or maybe both), you don't see that error.
//1 create a data base connection
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if (!$con) {
die('mysqli connection failed: ' . mysql_error() );
}
//2 connect with a data base
$db_select = mysqli_select_db($con , DB_NAME);
if (!$db_select) {
die('data base selection failed: ' . mysql_error() );
}
//3 create query
$result = mysqli_query($con, "select * from subjects");
if (!$result) {
die('query not successed: ' . mysql_error() );
}
//4 use the returned data
while ($row = mysqli_fetch_array($result)) {
echo $row['menu_name'] . " " . $row['position'] . "<br>" ;
}
//5 close connection...
if (isset($con)) {
mysqli_close($con);
}
Run this code if you have any query then feel free to ask me.
First check your php version
echo 'Current PHP version: ' . phpversion();exit;
if it is above 5.5 and even not working
then write script in your php file phpinfo(INFO_MODULES);exit;
it show all about php and check Mysqli listed or not. if not then inform to our server admministrator or if you have access then go to phpini file and enable mysqli (remove semicolon from it)
Try this:
$dbc = # mysql_connect('localhost', 'root', '') or exit('Not connecting.');

Check if MySQL server is able to accept connections

What is the best way to check, from PHP, if connection to a MySQL server will succeed? I've seen some solutions that first try to open a socket connection (with fsockopen) and connect to MySQL (via whatever extension you are using) only if the socket connection was successful. I'm not too sure about this since you have to make two connections every time, does that hammer the server too much?
My problem is that if my MySQL server locks-up or stops working for whatever reason the web page just stops working (it load for a long time and then usually comes back with a 504 gateway time-out error). I'd like to display a user friendly error message if MySQL is not available. This would also, hopefully, avoid MySQL being hammered even more if it is already struggling, as new clients won't connect to it until the server comes back up.
I'm using MySQLi extension if that is relevant.
What your need is the MYSQLI_OPT_CONNECT_TIMEOUT specify in mysqli::options
details
<?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);
}
/*
* 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());
}
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();
?>
From http://www.php.net/manual/en/mysqli.connect.php

Categories