So, a few months ago Celauran suggested I start learning Prepared Statements. Today, I spent a lot of time looking around, but can't seem to find a simple example that shows how to insert data from a form using prepared statements. So, I created my own. I was able to use one example I found to get data into a db, but when I removed the hard-coded fields and put in my form fields, the data doesn't save to the db.
Could someone please take a look at my simple learning script and fix it to make it work, so I can learn and build upon it? Thanks in advance!
Code: Select all
<?php
$servername = "localhost";
$username = "admin";
$password = "admin";
$dbname = "prepared_statements";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// ****************************************************************************
$sql = "DROP TABLE if exists MyGuests" ;
mysqli_query($conn, $sql);
$sql = "CREATE TABLE MyGuests (
firstname varchar(32),
lastname varchar(32),
email varchar(128),
PRIMARY KEY (email)
)";
mysqli_query($conn, $sql);
echo "MyGuests Successfuly Created<br><br>";
// ****************************************************************************
echo "<pre>"; print_r($_POST); echo "</pre>";
if(isset($_POST['save'])) {
// prepare
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
// bind
$stmt->bind_param("sss", $firstname, $lastname, $email);
$stmt->execute(); // not sure if this is suppose to be here or not
}
$stmt->close();
$conn->close();
?>
<form name="form" id="form" method="post">
<table style="width: 90%; padding: 5px; border-spacing: 15px;">
<tr>
<td style="width: 200px; white-space: nowrap;">First Name</td>
<td><input name="firstname" value="<?=$firstname;?>"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input name="lastname" value="<?=$lastname;?>"></td>
</tr>
<tr>
<td>Email Address</td>
<td><input name="email" value="<?=$email;?>"></td>
</tr>
<tr><td><input type="submit" name="save" value="Save Entries"/></td>
</tr>
</table>
</form>