PHP SQL Tutorial
PHP is a programming language of the Internet. Part of creating dynamic pages is using SQL in PHP to retrieve data from the server. This code is produced in the PHP pages where it calls the database server. A typical choice for database servers using PHP is MySQL, a free database application available to download. Some web hosts offer MySQL for free with their service.
-
Setup the Database Connection
-
To call MySQL from PHP, make a connection string in the application. The best practice for creating a username and password in MySQL is to make only one user for the PHP web pages. This creates better security for the administrator. If the username for the PHP pages is hacked, then the administrator can change that one user's password without the need to change multiple profiles. The username and password is needed for the application. The following code sets up the connection to the MySQL database in PHP:
$username = "my_user";
$pass = "pass";
$database="myDB";
mysql_connect(server,$username,$pass);
@mysql_select_db($database) or die( "Could not connect to the MySQL server");The first three lines are strings that setup the connection's username, password and database name. The server name is indicated in the connection call named "mysql_connect" in the code. Finally, the last line is the call to the database for a connection. If the connection is unable to be made from a bad server name or username and password, the application prints the "die" message.
Calling MySQL with a Query
-
Once the connection has been made, the application can send a query to the MySQL server. A query is made using a string, but the query must follow standard MySQL syntax. Below is a sample query used to retrieve data from the database:
$myquery = "select customer_name from customer";
mysql_query($query);
mysql_close();The first line is a string character that sets up the query. The query is very basic, retrieving a list of customers from the customer table. The second line actually calls the database and retrieves the information. Finally, the close function is called to close the database connection. This is an important part of performance since connections that aren't closed take up memory on the host server and can slow down an application.
-