mysql not connect with php scripts?
<?php
$cons=mysql_connect("localhost","root","");
mysql_select_db("infogallery") or die('Not Connected to the data base:'.mysql_error());
?>
I write above code for connection with mysql but when i run this scripts..nothing display on the brouser...what can i do for the c开发者_如何转开发onnection with mysql....
If nothing is displayed, then it means it succeeded. Add more code which queries the database and displays some results.
Don't connect as the root account. Create an account specifically for playing around with.
Once you've done that, modify your code as follows:
$cons = mysql_connect('localhost', 'username', 'password');
if ($cons === FALSE) {
die("Failed to connect to MySQL: " . mysql_error());
}
mysql_select_db(etc.....);
You don't check if the connection failed, then try to do a database operation on that potentially failed connection. The or die(...)
you have will only show the error caused by the select
attempt, and the error message from the failed connection will be lost.
I like to just do
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("infogallery") or die(mysql_error());
echo "So far, so good.";
How about something like the following:
<?php
try {
$cons = mysql_connect("localhost","username","password");
} catch ($e) {
die('Failed to connect to the database: ' . mysql_error());
}
try {
mysql_select_db("infogallery", $cons);
} catch ($e) {
die('Failed to select the database: ' . mysql_error());
}
?>
精彩评论