One of the most compelling things PHP has going for it is it support for a wide variety of databases. And this week, PHP 101 is going to take advantage of that database support to create dynamic data-driven Web sites. This primer covers different techniques to select, insert and delete records, together with some tips to track and squash bugs when building SQL-driven sites.
Thus far, we've simply been using SELECT queries to pull information out of a database. But how about putting something in?
SQL aficionados know that this happens via an INSERT query - and our next example demonstrates how you can use an HTML form to insert data into the database.
<?
// if form has not been submitted, display form
if (!$submit)
{
?>
<html>
<head>
<basefont
face=Arial>
</head>
<body>
<h3>Enter your bookmarks:</h3>
<form
method="POST" action="push.php4">
<table>
<tr>
<td>
Username
</td>
<td>
<input
name="username" length="10" maxlength="30">
</td>
</tr>
<tr>
<td>
Web
site
</td>
<td>
<input name="title1" length="30" maxlength="30">
</td>
</tr>
<tr>
<td>
URL
</td>
<td>
<input
name="url1" length="30">
</td>
</tr>
<tr>
<td>
Web site
</td>
<td>
<input
name="title2" length="30" maxlength="30">
</td>
</tr>
<tr>
<td>
URL
</td>
<td>
<input
name="url2" length="30">
</td>
</tr>
<tr>
<td>
Web site
</td>
<td>
<input
name="title3" length="30" maxlength="30">
</td>
</tr>
<tr>
<td>
URL
</td>
<td>
<input
name="url3" length="30">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input
type="submit" name="submit" value="Submit">
</td>
</tr>
</table>
</form>
</body>
</html>
<?
}
//
or process form input
else
{
?>
<?php
// connect to database
$connection =
mysql_connect("localhost", "test", "test") or
die("Invalid
server or user");
//
select database
mysql_select_db("php101",$connection);
// formulate and run query
$query
= "insert into
url_list(uid,title1,url1,title2,url2,title3,url3)
values('$username','$title1','$url1','$title2','$url2','$tit
le3','$url3')";
$result
= mysql_query($query,$connection) or die("Error in
query");
?>
<html>
<head>
<basefont
face=Arial>
</head>
<body>
<center>
<h3>Success!</43>
<table>
<tr>
<td>
<?php
echo $username; ?>'s bookmarks have been saved.
</td>
</tr>
</center>
</body>
</html>
<?
}
?>
This time around, we've demonstrated yet another PHP function - mysql_select_db(),
which allows you to specify the database which will be used when connecting to the database. And since you've specified the database, you can use mysql_query() instead of mysql_db_query() - while the latter needs the database name as parameter [as you've seen in the examples above], the former simply needs the query string and the connection identifier.
As you can see, inserting a record into the database is very straightforward - simply fire the query and your INSERT statement will be executed. The only way to find out if the INSERT was successful is to check the value of the variable $result - if the variable isn't set, it implies that something didn't go as planned.