Data driven websites in PHP using MySQL
|
By Joe Barber |
Connecting to a database
In MySQL, set up a user for your database – in the example below, our database is called ‘Customers’, our user is called ‘web’ with a password of ‘password’ (you should choose a much more secure password than this).
Once the user is set up, create the following file called db.cfg.php in which these parameters will be stored to allow your PHP scripts to connect to your database.
|
/* localhost can be replaced with the IP address of the database server */ Fig. 1 db.cfg.php |
For security, save this file in a different directory to your main codebase; in this example we will save the file under /home/DBConnect/db.cfg.php. The next step is to write a PHP script that tries to connect to the Customers database through using this file:
|
define(“DB_DIR”,”/home/DBConnect”); if($conn = @mysql_connect(DB_HOST,DB_USER,DB_PASS)) { if(!$success) { Fig. 2 Connecting to the database |
Calling the database using SQL
If your page shows the message “Connection established to the database!”, then your data-driven site is up and running, and it’s time to make some calls to the database!
|
$sql = “SELECT CustomerId, CustomerName FROM Customers”; if(!$query) { $result = array(); while($sql = @mysql_fetch_array($query,MYSQL_ASSOC)) { if ($result) { Fig. 3 A simple SELECT query returning all customer IDs and customer names from the Customers table in the Customers database |
|
$name = “John Smith”; $sql = “INSERT INTO Customers (CustomerName, CustomerEmail) if(!$query) { /* make a note of the customer ID that has just been inserted for future use if necessary */ Fig. 4 A simple INSERT query adding a new customer ‘John Smith’ to the Customers table in the Customers database |

No comments yet.