I would love to check if i can connect to database using given username, password, and database host.
So far i was trying:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$conndatabase = mysql_select_db($dbname);
if(!mysql_ping($conn) || !$conndatabase){
//do something when cant connect
} else {
//do something when you connected
}
It works when i give bad $dbname, cuz it cant select this database. But when i give wrong host, username or password, it will give me white page with errors. For example:
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'rootx'#'localhost' (using password: YES) in C:\xampp\htdocs\strony\planer\config\opendb.php on line 6
Warning: mysql_ping() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\strony\planer\grupy.php on line 3
Question:
Is there a way to check if i can connect using given data without errors? It just gives errors before getting to mysql_ping()
EDIT
After trying Mike Brant solution, i think i could have explained it wrong. I am trying to connect to database, and if it lets me, it shows user page he wanted to access, but when it's impossible, it redirects him to the other page, to modify database information.
if(!$conndatabase){
header('Location: index.php');
}
I am using that for checking if database exists. But if i try if(!$conn) or something similar, its too late, because i got errors displayed on $conn = mysql_connect($dbhost, $dbuser, $dbpass). So i cant redirect, as it gives me
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'root'#'localhost'~~
Warning: Cannot modify header information - headers already sent by~~
Yes. Just test the value of $conn. If it is false then the connection failed, and you shouldn't even try to proceed to the db selection step.
Your code might look like this:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (false === $conn) {
throw new Exception('Could not connect to database: ' . mysql_error());
}
$db_select = mysql_select_db($dbname. $conn);
if (false === $db_select) {
throw new Exception('Could not select database: ' . mysql_error($conn));
}
The PHP documentation is very clear on this: http://php.net/manual/en/function.mysql-connect.php
By the way, you should look at using mysqli or PDO as mysql_* functions are deprecated.
Try to debug your connection with something like
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link){
die('Could not connect: ' . mysql_error());
}
In this way you can easilly check if connection is estabilished otherwise you will print an error.
Then I would like to remember you that mysql_ functions are deprecated so i would advise you to switch to mysqli or PDO
When you look on my edit in question, you can see those answers didn't solve my problem completely. I still lacked some way to avoid errors. That's where i used error_reporting(0);.
I am not sure if that's best solution, but it works like a charm for me.
So the code for everything i tried to achieve looks like that:
opendb.php file
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password123';
$dbname = 'databasename';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$conndatabase = mysql_select_db($dbname);
?>
And there on the site i am checking connection:
<?php
error_reporting(0);
include 'opendb.php';
if(!mysql_ping($conn) || !$conndatabase){
header('Location: index.php'); //or any other site where you can config your database connection information.
}
So yeah, thats complete solution to my problem. I guess i could use !$conn instead of !mysql_ping($conn) with same result.
As has already been said, it’s the first example on the PHP manual page for the mysql_connect function.
Secondly, you should be either using the mysqli_ functions or PDO, as the mysql_ functions are deprecated and currently being phased out.
To check a connection with PDO:
try {
$db = new PDO('mysql:host=127.0.0.1;dbname=dbname', 'user', 'pass');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
header('HTTP/1.1 500 Internal Server Error');
die($e->getMessage());
}
Related
I've looked through StackOverflow for an answer to this and have so far come up empty handed. I know some have had a similar issue, but so far none of the responses to the issues have worked.
So I work on two sites, both of which are on the same host with the same PHP Admin set up (different accounts and domains, sites are not affiliated). One of them uses MySqli perfectly, without issues, while the other either gives a database selection failure, localhost access denied with password as "NO" or a blank page when I attempt to replace the MySql with MySqli.
The deprecated code:
$host = "LOCALHOST";
$usr = "USER";
$pwd = "PASSWORD";
$dbname = "DATABASE";
$connection = #mysql_connect($host,$usr,$pwd);
if(!$connection){
die("No connection.");
}
mysql_select_db($dbname,$connection);
The MySqli I am attempting (identical to the site that MySqli works perfectly on):
$host = "LOCALHOST";
$usr = "USER";
$pwd = "PASSWORD";
$dbname = "DATABASE";
$connection = mysqli_connect($host,$usr,$pwd);
if (!$connection) {
die("No connection.");
}
$db_select = mysqli_select_db($connection, $dbname);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
So the PHP error codes did not work at all and it had nothing to do with the local host or port, so I first checked to make sure mysqli_connect was on. Next, I ran a simple test where I echoed a random word before each mysqli command.
echo 'Passed.';
global $c_mysqli;
$conn = new mysqli($host, $usr, $pwd, $dbname);
echo '<br>Passed global mysqli.';
I found that my second pass was not working, and then proceeded to do an error message. An error showed up then. However, nothing I did fixed the issue... then I realized that one of my files, the header file, is the meat and potatoes and if it were to fail then everything else would fail too.
Sure enough, one of my lines of code contained a mysql connection and not mysqli. Long story short, double check and triple check to make sure that all
$statement = mysql_query("STATEMENT");
$query = mysql_fetch_array($statement);
Appear as
$statement = $conn->query("STATEMENT");
$query = mysqli_fetch_array($statement);
I am learning MySQL/PHP and I cannot figure out how to connect to MySQL on my localhost. I have written a short bit of code and I included root as my user name and root as my password because I have not set these elements yet (as far as I know). I feel that perhaps I am missing something in regards to the username/password combination. However, I feel that this should not be an issue because I have not tampered with the default conditions.
I need some help.
My code is below:
<?php
try {
$db = new PDO("mysql:host=localhost;dbname=shirts4max;port=3306", "root", "root");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf-8'");
} catch (Exception $e) {
echo "Could not connect to the database.";var_dump($e);
exit;
}
I am only seeing the error message on my page:
"Could not connect to the database."
Thank for reading. Please help me Obiwan.
Show the real error. Avoid using root except for maintenance.
From the PDO Manual page here, modified for you
<?php
$dsn = 'mysql:dbname=shirts4max;host=localhost';
$user = 'root';
$password = 'root';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Have you tried connecting via command line using: mysql -uroot -proot -hlocalhost -p3306? If you can't connect that way, the PDO connection won't go through either. Playing with the connection info via command line gives you a nice easy way to find what works, then include it in your code. Also, if you've not set the user/pw, it's possible there isn't one currently, so you wouldn't need those parameters at all.
I creat a database in cpanel and write small php code.
<?php
$dbhost='localhost';
$dbuser='-------';
$dbpass='*******';
$db = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_set_charset('utf8',$db);
if(!$db){
echo 'can not connect to server';
}
else{
$database = '--------_ps';
$select = mysql_select_db($database);
if($select){
echo 'database selected. <br/>';
}
else{
echo 'database not select. <br/>';
}
mysql_close($db);
}
?>
I see database not select, When I change --------_ps database to phpmyadmin data base 'Database operations
information_schema' echo database selected.
I am not beginner on php but I don't know any way to solve this.
Please help me.
Try this code -witch also provides some basic feedback as to what errors your script may encounter:
<?php
...
$conn = #mysql_connect($dbhost, $dbuser, $dbpass) or die("Could not connect to the Database Server");
mysql_set_charset('utf8', $conn );
mysql_select_db($database, $conn) or die("Could not find the Database");
...
?>
Now, the above script works. If you still encounter problems, can you please give some feedback with the error log of your web server?
One more thing: Make sure you have created the database correctly with the phpMyAdmin, AND also have set the user with the credentials you are using...
I am attempting to connect to a mySQL database running on my local computer using a local test server set up using XAMPP. I am just using the root account which has no password assigned. I tried it as below and everything appears to work fine. I got my message echoed out to say I had successfully connected. I then tried to force an error by entering anything else in as the host, username or password and it still echoes "connection successful".
This is the code I am using to connect:
<?php
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$myConn = mysql_connect($db_host, $db_username, $db_password) or die('Connection error: '.mysql_error());
echo 'connection successful';
?>
I was wondering whether it is me or maybe the install of apache/mySQL that I am using that is causing such an absurdity.
Something must be screwed up with your install:
marc#panic:~$ php -a
php > $x = mysql_connect('bleargh', 'foo', 'bar') or die(mysql_error());
PHP Warning: mysql_connect(): Unknown MySQL server host 'bleargh' (2) in php shell code on line 1
Unknown MySQL server host 'bleargh' (2)marc#panic:~$
About all I can think of is you've got a DNS server that returns a valid address for ALL lookups, causing all hostnames to resolve.
try this one
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$con = mysql_connect($db_host,$db_username,$db_passwd);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
echo 'connection successful';
mysql_close($con);
?>
It will always echo 'connection successful' because you aren't checking the status of the connection.
if (!$myConn) {
echo 'Sorry, there was an error '.mysql_error();
} else {
echo 'connection successful';
}
Depending on how you executed the code, you might be running into this:
If a second call is made to mysql_connect() with the same arguments,
no new link will be established, but instead, the link identifier of
the already opened link will be returned. The new_link parameter
modifies this behavior and makes mysql_connect() always open a new
link, even if mysql_connect() was called before with the same
parameters. In SQL safe mode, this parameter is ignored.
So, either do an explicit check or:
$myConn = mysql_connect($db_host, $db_username, $db_password, true) or die('Connection error: '.mysql_error());
I'm new to PHP and have installed on Linux to boot (also a newbie).
Anyway, PHP is working...
<?
$myVar = "test";
echo($myVar);
?>
... works just fine.
But...
<?
$dbhost = "localhost";
$dbuser = "myuser";
$dbpass = "mypass";
$dbname = "mydb";
echo($dbhost . "-" . $dbuser . "-" . $dbpass . "-" . $dbname);
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to MySQL");
print $conn;
mysql_close($conn);
phpInfo();
?>
... does nothing. Nor errors, nothing. Its as if the code isn't even there.
Any help?
Try to do the following:
First make sure display_errors is turned on in your php configuration file. Also set the level of error_reporting to show all errors, including strict (error_reporting = E_ALL|E_STRICT). After you make changes, restart your webserver.
Run phpinfo(), and check that the mysql extension is installed and working. If it isn't make sure that you uncommented it in the php configuration file (again, remember to restart apache after each change to the configuration file).
At this point MySQL should be loaded and working, and you should be able to tell from the error (if it persists) what's the problem.
Try also dumping the contents of the connection result ($conn) to see what it contains.
In general, I'd recommend using long php tags (<?php and not <?) since it is more portable (short tags are off by default in PHP 5 installations).
Try adding this to the top of your code:
error_reporting(E_ALL);
If it does nothing, doesn't that mean that it connected fine? What output do you expect out of that statement?
You could try
error_reporting(E_ALL);
$conn = mysql_connect("localhost", "myusername", "mypassword");
if(!$conn) {
echo 'Unable to connect';
} else {
echo 'Connected to database';
}
var_dump($conn);
edit: Addressing the comment saying that you have a mysql query setup, if you are not seeing "success" it means something is wrong with your query. Add to the above
$sth = mysql_query("SELECT * FROM tablename");
if(!$sth) {
echo 'unable to query: ' . mysql_error();
} else {
echo 'success';
}
Is there more code than you're showing us? The block you have just sets up a connection. You won't see anything at all if it succeeds, you have to use $conn to do something.
To confirm, try changing your password to a deliberately wrong value, and then see if you get an error. If you do, the code works just fine.
Connecting to a database with
$conn = mysql_connect("localhost", "myusername", "mypassword") or die("Unable to connect");
will have no (visible( results if the connection was made succesfully. However, once you run this statement, you can use the other mysql functions to make make queries to the database.
Connecting to a database tells your program "hey, I want to talk to this database".
This code is supposed to create a db connection, nothing else. What do you expect to see?
Try this
<?php
$conn = mysql_connect("localhost", "myusername", "mypassword")
or die("Unable to connect");
print("code sample");
print $conn;
?>
It should print you something like "resource #1"...
And then you may use that connection to communicate with db server