Quick Reach
Establishing DB connection with mysql_connect
/*
PHP provides built-in function mysql_connect to establish database connection with MySQL database. See the syntax below
connection mysql_connect(server,user,passwd,new_link,client_flag);
We have assumed that you have created a database with:
database name = testdb
user name = tesuser
password = testpassword
at your local system.
In that case:
DB host = “localhost”
Connecting to MySQL Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <?php $dbhostname = 'localhost'; $dbusername = ‘tesuser’; $dbpassword = 'testpassword'; $conn = mysql_connect($dbhostname, $dbusername, $dbpassword); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'MySQL Connected successfully'; mysql_close($conn); ?> |
Connecting to Database
After establishing connection to MySQL, its time to connect to working database, testdb
Syntax
mysql_select_db(“database_name”)
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <?php $dbhostname = 'localhost'; $dbusername = ‘tesuser’; $dbpassword = 'testpassword'; $conn = mysql_connect($dbhostname, $dbusername, $dbpassword); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'MySQL Connected successfully'."<BR>" ; mysql_select_db("testdb") or die(mysql_error()); echo "Connected to Database"; ?> |
Output
MySQL Connected successfully
Connected to Database
Now as MySQL is connected and database is connected/chosen as well, its time to insert, update and delete operations at tables of database.
Leave A Comment?