PHP/MySQL : Creating a guest book
Olivier Roble
Inserting User Data into the Table
Once the validity of the user data is confirmed, we can insert them into our database. We need to build a complete SQL query,
using the following structure:
INSERT INTO [tablename] ([column1], [column2]) VALUES ([value1], [value2])
By doing so, we ask the database engine to insert a new row (
INSERT) in the
tablename table, using the
value1 and
value2 values for the
column1 and
column2 columns, respectively. In our case, we get the following query:
INSERT INTO impression (name, email, impression, date, comments) VALUES ('$name', '$email', 'impression', '$date', '$comments')
To run this query, you must first store the query string in a variable before submitting it to the MySQL server through the
mysql_query function. Here is the final insertion page:
1 :<html>
2 : <head><title>PHP workshop for form management: ajoutimp.php</title><head>
3 : <body>
4 : <?php
5 : $db = mysql_connect();
6 : $continu=1;
7 : if ($nom == "")
8 : {
9 : print("Your name is needed !<br>");
10: $continu=0;
11: }
[...]
22: if ($continu == 1)
23: {
24: $date=date("Y-m-d");
25: $sql="INSERT INTO impression (name, email, impression, date, comments) VALUES ('$name', '$email', 'impression', '$date', '$comments')";
26: mysql_query($sql, $db);
27: print("Thank you for giving me your impressions !") ;
28: }
29: else
30: {
31: print("<a href=impressions.html>back</a>");
32: }
33: ?>
34: </body>
35: </html>
If all the input fields have received a value, the
$continu variable contains the value
1. Once this value has been checked (line 22), we can execute the query to insert the data (lines 25 and 26) and display a
message to thank the visitor (line 27).
Conversely, if the
$continu variable holds
0, we simply display a link to revert to the fill-in form (line 29). The error messages due to bad input will have been displayed
as the data are checked.