Skip to content

Instantly share code, notes, and snippets.

@asathoor
Created September 26, 2017 06:22
Show Gist options
  • Save asathoor/df19a8cff8ff5cd5e2d5805a251e16c3 to your computer and use it in GitHub Desktop.
Save asathoor/df19a8cff8ff5cd5e2d5805a251e16c3 to your computer and use it in GitHub Desktop.
SQL INSERT via PHP and HTML5 form

SQL INSERT via HTML5 form

A very basic form. Remember to include the HTML head section etc. - e.g. from boilerplate or similar.

Security

Cleanse the user input in action.php via:

$fn =  addslashes( strip_tags( $fn ) );

This was omited in order to get a more readable code.

<div>
<?php
/*
File: action.php
Purpose: INSERT INTO ...
Security: addslashes, removetags missing
*/
require_once 'db.php'; // database connection
if($_GET) {
$fn = $_GET['firstName']; // fra form
$ln = $_GET['lastName'];
$email = "test@test.dk"; // add a form field ...
// format the sql
$sql = "INSERT INTO `navne` (`navne_id`, `fornavn`, `efternavn`, `email`) VALUES (NULL, '"
. $fn
. "', '"
. $ln
. "', 'www@www.dk');";
// INSERT
if( $insert = $mysqli->query($sql) ){
echo "<p>New actor added: $fn $ln - Gee thanx a lot.</p>";
echo "<h2>SQL</h2> <pre>" . $sql ."</pre>";
} else {
echo "INSERT not possible. Check your SQL.";
}
}
else {
echo "<p>Error: Use the form please. No GET got.</p>";
}
?>
</div>
<!-- Input form -->
<form action="action.php" method="get">
<fieldset>
<legend>Enter an actor here</legend>
First Name <input type="text" name="firstName"><br>
Last Name <input type="text" name="lastName"><br>
<input type="submit" name="submit" value="submit"><button name="Cancel" value="Cancel" type="reset">Cancel</button>
</fieldset>
</form>
@asathoor
Copy link
Author

NB: db.php

<?php
// CONNECT TO THE SAKILA DATABASE

$mysqli = new mysqli("localhost", 
	"root", 
	"password",
	"database"); // creates the object

if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; // if error messages
}

/* test your connection */
echo "Your're connected to the database via: " 
. $mysqli->host_info 
. "\n";
?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment