Database use with PHP and mySQL
Here is example to create the table to the database:
<?php
include ‘config.php’;
include ‘opendb.php’;
$query = ‘CREATE TABLE hoppy (car VARCHAR(20), model VARCHAR(20),
year VARCHAR(4), horsepower VARCHAR(4), torx VARCHAR(4))’;
$result = mysql_query($query);
include ‘closedb.php’;
echo “You created a new table hoppy.<br />”;
?>
Config.php
<?php
// example of config.php
$dbhost = ‘localhost’;
$dbuser = ‘username’;
$dbpass = ‘password’;
$dbname = ‘phptest’;
?>
Opendb.php
<?php
// This is an example opendb.php
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die (’Error connecting to mysql’);
mysql_select_db($dbname);
?>
Closedb.php
<?php
// an example of closedb.php
mysql_close($conn);
?>
Example HTML form
<html>
<head>
<title>Form output by PHP</title>
</head>
<body>
<form method=”POST” action=”inputform.php”>
<p>
Car <input type=”text” name=”car” size=”20″>
Model <input type=”text” name=”model” size=”20″>
Year <input type=”text” name=”year” size=”20″>
Horsepower <input type=”text” name=”horsepower” size=”4″>
Torx <input type=”text” name=”torx” size=”3″>
<input type=”submit” value=”Submit”>
</p>
</form>
</body>
</html>
HTML form is calling the inputform.php, which insert the data the database
Inputform.php
<html><body>
<?php
include ‘config.php’;
include ‘opendb.php’;
$car = $_POST['car'];
$model = $_POST['model'];
$year = $_POST['year'];
$horsepower = $_POST['horsepower'];
$torx = $_POST['torx'];
$query = “INSERT INTO hobby (car, model, year, horsepower, torx)
VALUES (’$car’, ‘$model’, ‘$year’, ‘$horsepower’, ‘$torx’)”;
mysql_query($query) or die(’Error, insert query failed’);
include ‘closedb.php’;
echo “You insert “. $car . ” ” . $item . “.<br />”;
echo “Thank you for inserting information to my database”;
?>
</body></html>
It would also be nice to see that does that code really added something to the database. We can use PHP to check the content of the database.
This PHP code select all the table information on the alphabetical order by “car” and print out information on the table format
Select_all.php
<?php
include ‘config.php’;
include ‘opendb.php’;
$query = “select * from hobby order by car”;
$result = mysql_query($query);
?>
<table cellspacing=0 cellpadding=4 border=1>
<tr>
<th>Car</th>
<th>Model</th>
<th>Year</th>
<th>Horsepower</th>
<th>Torx</th>
</tr>
<?php
for($counter = 0; $counter < mysql_num_rows($result); $counter++) {
?>
<tr>
<td><?php echo mysql_result($result,$counter,”car”)?></td>
<td><?php echo mysql_result($result,$counter,”model”)?></td>
<td><?php echo mysql_result($result,$counter,”year”)?> </td>
<td><?php echo mysql_result($result,$counter,”horsepower”)?> </td>
<td><?php echo mysql_result($result,$counter,”torx”)?> </td>
</tr>
<?php
}
?>
</table>
<?php
include ‘closedb.php’;
?>