When trying to connect to my database using PHP I am getting an error.
$connect = mysql_connect("localhost","username","password") or die ("Couldn't Connect!");
mysql_select_db("databasename") or die ("Couldnt find database");
When I try running the script it keeps saying 'Couldnt find database' which means that I am connecting to the server but my database won't connect.
Am I doing something wrong here? I have pretty much copied and pasted my database name from Cpanel so I know there aren't any mistakes. But in Cpanel it is displayed as 'mywebsite'_database
Any ideas?
You specify in your question that your database is called:
'mywebsite'_database
If this is the case, then you need to change your code to
// Connect to the database
$connect = mysql_connect("localhost","username","password") or die ("Couldn't Connect!");
// Select the database
mysql_select_db("mywebsite_databasename",$connect) or die ("Couldnt find database");
If the above method does not work then I would advise debugging your connection by listing the databases for that particular user. Do this like so:
// Connect to the database
$connect = mysql_connect("localhost","username","password") or die ("Couldn't Connect!");
// Get all the databases for this particular user
$databases = mysql_list_dbs($connect);
// Loop through the databases and write them on the screen
while($database = mysql_fetch_assoc($databases)) {
echo $database['Database']."\n";
}
exit;
mysql_select_db("mywebsite_database")
Print out the names of all the databases in the server (using mysql_list_dbs).
Find the correct database name and replace "databasename" with it.
$connect = mysql_connect("localhost","username","password") or die ("Couldn't Connect!");
$db_list = mysql_list_dbs($connect);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
}
mysql_select_db("databasename", $connect) or die ("Couldnt find database");
I recommend using MySQLi extension as mysql_* is currently in a depreciation process.
I hope this helps
Related
I have website I was build it from scratch using PHP/MYSQL but unfortunately I got a lot of mysql DB disconnect "not conect", I'm sure about DB Name, user and Password .. My config file below :
$conectdb = mysql_connect("localhost","user","pass") or die ("not conect");
mysql_set_charset('utf8',$conectdb);
$selectdb = mysql_select_db("DB_name",$conectdb)or die ("selected DB");
$charset = mysql_client_encoding($conectdb);
header('X-Frame-Options: SAMEORIGIN');
< ?php
$connection = mysql_connect(localhost","user","password") or die ("Couldn't connect to the server!");
mysql_select_db("users", $connection) or die ("Couldn't connect to the database!");
I used the above code above to try and connect to my database but keep getting an error in line 2 where mysql_connect(localhost)---- I've typed in my localhost name correctly why won't it work?
please help this is my first day ever dealing with php and databases.
thanks in advance.
Missing a quote in localhost:
$connection = mysql_connect("localhost","user","password") or die ("Couldn't connect to the server!");
The correct way to do it is:
<?php
$connexion = mysql_connect("localhost", "user", "password")
or die("Couldn't connect to the database! : " . mysql_error());
mysql_close($connexion);
?>
Nota Bene:
Rather use mysqli_ or PDO. What you are using here is deprecacted for security reasons.
Got a problem! Though I found almost similar threads but none helped :(
I've written a php script to fetch the number of registered users from my MySQL database. The script is working great in my localhost; it is using the given username,pass and host name which are "root", "root", and "localhost" respectively, but the script is not using the given username/pass/host rather using root#localhost (password: NO) in Live server.
In the Live server I created a MySQL user, set an different password, and hostname there is of course not localhost. I updated the script with my newly created mysql users data. BUT, whenever I run the script, I see that the script is still using "root", "root", and "localhost"!!
take a look at the script:
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
$db = mysql_select_db ("regdb",$conn); //Oops, actually it was written this way in the script. I misstyped it previously. now edited as it is in the script.
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ");
while ($row = mysql_fetch_array($query)):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
-- Some says to change the default username and pass in the config.ini.php file located in phpMyAdmin directory. Would this help?? I didn't try this because either my hosting provider didn't give me privilege to access that directory (because I am using free hosting for testing scripts) or I simply didn't find it :(
Please help....
Foreword: The MySQL extension is marked as deprecated, better use mysqli or PDO
Though you store the connection resource in $conn you're not using it in your call to mysql_query() and you're not checking the return value of mysql_connect(), i.e. if the connection fails for some reason mysql_query() "is free" to establish a new default connection.
<?php
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
if ( !$conn ) {
die(mysql_error()); // or a more sophisticated error handling....
}
$db = mysql_select_db ("regdb", $conn);
if ( !$db ) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
while ( false!=($row=mysql_fetch_array($query)) ):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
edit: It looks like you're processing only one row.
Either move the echo line into the while-loop or (if you really only want one record) better say so in the sql statement and get rid of the loop, e.g.
// Query to fetch data
// make it "easier" for the MySQL server by limiting the result set to one record
$query = mysql_query("SELECT * FROM regd LIMIT 1", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
// fetch data and output
$row=mysql_fetch_array($query);
if ( !$row ) {
echo 'no record found';
}
else {
echo htmlspecialchars($row['total_regd']);
}
First of all:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
What is your mysql_error()? :)
I've seen a few errors like this, but I found no answer.
Unable to connect to database: Access denied for user ''#'localhost' to database 'socialdb'
socialdb is my database. The "Unable to connect to database:" part is located here.
$db = mysql_select_db("socialdb",$con);
if(!$db) {
die ('Unable to connect to database: ' . mysql_error());
}
I don't know what's causing this. Here are my mysql_connect details
<?php
$con = mysql_connect("localhost");
if(!$con) {
die ('Error: ' . mysql_error());
}
I need to find the root. Thanks.
I DON'T HAVE A USERNAME OR PASSWORD FOR MySQL
Should it be this?
mysql_connect("localhost","","");
The error is pretty self-explanatory, you're not allowed to connect without specifying some credentials.
Change your call to mysql_connect() to something like this:
mysql_connect("localhost", "user", "password");
Your default credentials are most likely:
$con = mysql_connect("localhost","root","");
You're missing username and password parameter, should be:
$con = mysql_connect("localhost","username","password");
You did not specify a user in neither mysql_connect or your PHP configuration.
Either set mysql.default_user and mysql.default_password in your PHP configuration or use the appropriate arguments for mysql_connect.
mysql_connect takes 3 parameters
$con = mysql_connect("localhost", "dbuser", "password");
even if you are not having a user. there exist 'root' user
so use it
$con = mysql_connect('localhost','root','');
i am new in php and want to know the code for php mysql database connection code
Refer to the PHP documentation for mysql_connect.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
Here is the bare bone of it:
$db1 = mysql_connect( ... );
mysql_select_db('existing_db',$db1);
$db2 = mysql_connect( ... );
mysql_select_db('not_existing_db', $db2);
mysql_query(... , $db2);
More Info:
http://php.net/manual/en/function.mysql-connect.php
MySQL PHP Connect Tutorial
A Detailed Tutorial:
http://www.phpf1.com/tutorial/php-mysql-tutorial.html?page=1
<?php
mysql_connect("localhost", "username", "password") or die(mysql_error());
echo "Connection to the server was successful!<br/>";
mysql_select_db("test") or die(mysql_error());
echo "Database was selected!<br/>";
?>
Watch also mysqli,it's the "new way" of connecting to mysql
http://php.net/manual/en/book.mysqli.php
it has more functions and there are rumors that in php6 mysql will be deprecated for the mysqli implementation.
you can use it as an object(but if you're new also to OO it may be a little more difficult to understand)like this:
//--connection to the database--
$db=mysqli_connect('sql.mysqlhost.com','database_username','password','database_name');//you can also use $db=new mysqli(....) but mysql_connect does the same thing and it's more cler on what it's doing
//--a simple query--
if($result=$db::query('SELECT name,value FROM mytable')){//query ok
echo 'Select returned ',$result->num_rows,'rows<br/>';
while($row=$result->fetch_assoc()){//get one row in an assoc.array
echo 'Name:',$row['name'],' Value:',$row['value'],'<br/>';//print each row
}
$result->close();
}
else//query error
die('MYSQL ERROR:'.$db->error);
or with functions like in mysql
//--connection to the database--
$db=mysqli_connect('sql.mysqlhost.com','database_username','password','database_name');
//--a simple query--
if($result=mysql_query($db,'SELECT name,value FROM mytable')){//query ok
echo 'Select returned ',mysql_num_rows($result),'rows<br/>';
while($row=mysqli_fetch_assoc($result)){//get one row in an assoc.array
echo 'Name:',$row['name'],' Value:',$row['value'],'<br/>';//print each row
}
mysql_free_result($result);
}
else//query error
die('MYSQL ERROR:'.mysqli_connect_error());
You can also use a persistent mysql connection prepending 'p:' to the sql host,for example if your host is sql.myhost.com:
$db=mysqli_connect('p:sql.mysqlhost.com','database_username','password','database_name');
Using a persistent connection should give you a great performance boost and mysqli should handle the persistent connection a lot better than the normal mysql extension.
Remember to sanitize the input of your query to avoid SQL INJECTION,you can do like this:
$result=mysql_query($db,"SELECT name,value FROM mytable where name='".mysqli_real_escape_string($input_name)."'");
or using a prepared statement that's a little more complicated and it's better only if you repeat the same command multiple times only changing the input data.