how do i connect to mysql with php?

weaverosu

New member
I am using php and mysql (or at least trying to use) and am having problems connecting to my db? I am using the following php script...

<?php

$host = "localhost";
$user = "root";
$pass = "root";

$connect = mysql_connect("localhost", "root", "root");
if (!$connect) {
die("Could not connect:" . mysql_error());
}
echo "Connected successfully";
mysql_close($connect);
?>

but when I runit in my browser the screen is blank. I get neither of the echo's?
 
This is the code you should use:


<?php

$host = "localhost";
$user = "root";
$pass = "root";

$connect = mysql_connect("localhost", "root", "root") or die("Could not connect:" . mysql_error());

echo "Connected successfully";
mysql_close($connect);
?>

It's useless to do an "if" check after the mysql_connect because the script will "die" on any error. You should use the "or die" right after the mysql_connect statement. If there are errors on connection, the script won't reach the if.

You will see that the login credentials are wrong.
 
This is the code you should use:


<?php

$host = "localhost";
$user = "root";
$pass = "root";

$connect = mysql_connect("localhost", "root", "root") or die("Could not connect:" . mysql_error());

echo "Connected successfully";
mysql_close($connect);
?>

It's useless to do an "if" check after the mysql_connect because the script will "die" on any error. You should use the "or die" right after the mysql_connect statement. If there are errors on connection, the script won't reach the if.

You will see that the login credentials are wrong.
 
You just forget one thing !
Where is the database name ?

How to fix that :
<?php

$host = "localhost";
$user = "root";
$pass = "root";
$db = "Your Data Base Name";

$con= mysql_connect($host , $user, $pass) or die('Unable to connect');
mysql_select_db ($db,$con) or die('Unable to select');

?>

Good luck and have nice day !
 
Back
Top