Connect a PHP script to a MySQL Database. The first thing you need to do once you established you have permission to access the database is set your script to connect to the database server. $connect = mysql_connect("localhost","username","password"); The above PHP function "mysql_connect()" allows you to establish a connection to MySQL database server. Remember that if you are using a remote database: mysql_connect("192.168.1.10","username","password"); You must first have permission to access the database from your location. In MySQL to grant permission to a remote client you need to run the following code in MySQL. mysql > grant all on some_database.* to 'test'@'127.0.0.1' identified by 'test';
At this stage the next thing in your PHP script is to establish the name of the database you are connecting to. $connect = mysql_connect("localhost","username","password"); $database_name = "some_database"; mysql_select_db($database_name); You must call the above code before you try to interact with the database in any way. For example, if we wanted to access a database called "example" and read a simple Select statement to a PHP page. $connect = mysql_connect("localhost","username","password"); $database_name = "example"; mysql_select_db($database_name); $sql = "select Name from example.Name"; $result = mysql_query($sql); while($row = mysql_fetch_object($result)) { echo $row->Name; }
|