How do I connect to a MySQL server using PHP?
If you are planning to do some PHP coding, most likely you will need an answer to this question. Here is how you do it.
<?php
$dbhost = 'localhost';
$dbuser = 'username';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'books';
mysql_select_db($dbname);
//Do whatever you have to do with the database eg query, update, insert etc
mysql_close($conn);
?>
Hopefully that works like a breeze. If you are still having issues, please note that,
- 'localhost' is used as the server address when your php script is running on the same server which is often the case. However, if your database is located on a different server, you will have to use "$dbhost = 'othername.otherdomain.com:3306';" where 3306 is the default port number for mysql. It might be different, check with the host.
- Often your webhost prepend your database name and username with your username with the webhost. Suppose you use host your database with xyzwebhost.com using a username 'abc'. You log in using your 'abc' username and corresponding password and create a database named 'mydb' and create an user 'mydbuser'. The xyzwebhost will actually create a database named 'abc_mydb' and an user named 'abc_mydbuser'. In your php script you have to use 'abc_mydb' and 'abc_mydbuser'.
- Remember creating a database and a dbuser is not enough, you have to add the user to the appropriate database with proper permission.
- Selecting a database after you connect to the server is important otherwise your queries have no effect.
- Remember to close the connection once you are done.
0 comments:
Post a Comment