Let's Get Started with a PHP/MySQL Form Page!
- Open Notepad++
- Choose:
File -> New
- Copy the PHP Form Template (PHP) code (below)
- Paste that code into your new file
- Change the put-title-of-this-page-here
- Change the lines with the blanks:
$query = "____________________________";
$query .= "____________________________;";
to:
$query = "INSERT INTO dishes (dish_name, price, is_spicy) ";
$query .= "VALUES ('$name', $price, $isSpicy);";
- Click: File -> Save As
- Name your file: \www\mysqlform.php
- Change the
Save as type:
to: PHP Hypertext Preprocessor (*.php)
- Click: Save
- Visit your page (http://buffalo.edu/form.php) in your favorite web browser
- Make any changes
- Save your changes
- Fill in the form fields
- Submit your form
- View your
mysqlform.php
page to see if the addition worked
- Change:
$debug = 0;
to: $debug = 1;
- Add another record to see the debug messages
PHP Form Template (PHP)
<!doctype html>
<html>
<head>
<title>put-title-of-this-page-here</title>
</head>
<body>
<?php
$debug = 0;
if (isset($_POST['submit'])) {
if ($debug) {
foreach ($_POST as $postElement => $postValue) {
echo("\$_POST[$postElement] = $postValue<br/>\n");
}
}
$name = $_POST['Name'];
$price = $_POST['Price'];
$isSpicy = $_POST['isSpicy'];
$dbUsername = "your-localhost-username"; // probably 'root'
$dbPassword = "your-localhost-mysql-password"; // probably ''
$dbDatabase = "cda350"; // localhost database name
$dbServer = "localhost";
// Create a new server connection
$dbConn = new mysqli($dbServer, $dbUsername, $dbPassword, $dbDatabase);
// Create the query
$query = "____________________________";
$query .= "____________________________;";
if ($debug) { echo("$query<br/>\n"); }
// Send the query to MySQL
$result = $dbConn->query($query,MYSQLI_STORE_RESULT);
echo("$name ($price) record inserted!<br/>\n");
}
?>
<h1>My Dish Data Entry Form</h1>
<form id="dishForm" method="POST" action="mysqlform.php">
<fieldset>
<legend>Dish Information</legend>
<label for="Name">Name:</label>
<input id="Name" name="Name" type="text"/><br style="clear: both;"/>
<label for="Price">Price:</label>
<input id="Price" name="Price" type="text"/><br style="clear: both;"/>
<label for="isSpicy">Is Spicy?</label>
<Select id="isSpicy" name="isSpicy">
<option value="1">Yes</option>
<option value="0">No</option>
</select><br style="clear: both;"/>
</fieldset>
<label for="submit"></label>
<button id="submit" name="submit" type="submit"
value="Do it!">Do it!</button><br style="clear: both;"/>
</form>
</body>
</html>
Output