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());
Related
I am much confuse about 000webhost database uploading I have set my database at their and accessing it with username and password perfectly. Now trying to connect with through PHP code but i am failed, getting 500 error code and no details of the error although I have also logged exception message in my connection code nuto it only showing "A Connection error has occurred" and nothing more:
//DB Configuration
$hostName = 'localhost';
$dbUserName = 'id143984_jw_kioskuser';
$dbPassword = '***********';
$databaseName = 'id143984_jw_kiosk';
try{
$dbHandler = new PDO('mysql:host='. $hostName . ';dbname='. $databaseName, $dbUserName, $dbPassword);
}
catch(PDOException $ex){
echo '<h1>A Connection error has occurred.</h1><pre>', $e->getMessage() ,'</pre>';
echo $e->getMessage();
}
My current DB interface at 000webhost saying me that "Use localhost as connection hostname"
while in another post of 000WEbhost saying "Never use 'localhost' as your MySQL hostname! You can find your MySQL hostname by logging on to members area, entering control panel and clicking on MySQL icon."
HOw do i make successfull connection?
Finally i managed to get the answer through mysql query thanks to Show MySQL host via SQL Command Answer at stack
I run below query and got the host name and use it in my php it worked now.
select ##hostname;
show variables where Variable_name like '%host%';
$hostName = 'mysql6.000webhosting.com';
$dbUserName = 'id143984_jw_kioskuser';
$dbPassword = '***********';
$databaseName = 'id143984_jw_kiosk';
$con = mysql_connect($hostName,$dbUserName,$dbPassword);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}`enter code here`
mysql_select_db("$databaseName",$con);
this should give you the real reason and note the correct host name
if (!empty($_POST)) {
$host = $_POST['host'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$db = $_POST['db'];
echo '<pre>';
print_r($_POST);
$con = #mysqli_connect($host . ":3360", $user, $pass, $db);
// $con=#mysqli_connect('192.168.100.42','root','vertrigo','skates');
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
echo 'connected';
}
#mysqli_close($con);
}
I'm using this script to access remote db server in local(basically i want to access local db server through live webiste), howewer, I'm getting an error:
Failed to connect to MySQL: Unknown MySQL server host
'192.168.100.42:3360' (11004)
Please help to get out from this.
192.168.100.42 looks like a local IP. You'd need to try to connect to your static public IP and then forward port 3306 in your router to the 192.168.100.42 machine.
That's not your only problem;
Just because $_POST is not empty, don't assume it has those array keys set and not empty. Syntax like
if(isset($_POST['user'] && !empty($_POST['user'])))
Is much better.
Also, never use $_POST on any database interaction without sanitisation, and never connect to a database with the root user.
I don't know your exact application, but it's impossibly insecure.
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());
}
<?php
// MySQL database connection file
$SERVER = "127.0.0.1"; // MySQL SERVER
$USER = "root"; // MySQL USER
$PASSWORD = "admin"; // MySQL PASSWORD
$link = #mysql_connect($SERVER,$USER,$PASSWORD);
$db = mysql_select_db("website");
?>
This is a database connecting code for chat program but it not connecting,Can any one pls help me to correct this code?
Drop the # infront of mysql_connect, it's used to suppress error which you don't want.
Also you need to check the return value of mysql_connect which is there in $link and make sure that it is not false before you proceed and to a DB select. Calling the function mysql_error when an error occurs gives you the reason for the error.
$link = mysql_connect($SERVER,$USER,$PASSWORD);
if (!$link) {
die('Could not connect: ' . 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