I have a MySQL database and I am trying to insert data into it using a PHP form running on IIS on my Windows 10 machine. I have the code below in a .php file:
<?php
if (isset($_POST['submit'])) {
require "config.php";
try {
$connection = new PDO($dsn, $username, $password, $options);
// insert new user code will go here
$new_user = array(
"firstname" => $_POST['firstname'],
"lastname" => $_POST['lastname'],
"city" => $_POST['city'],
"country" => $_POST['country'],
"age" => $_POST['age']
);
$sql = sprintf(
"INSERT INTO %s (%s) values (%s)",
"users",
implode(", ", array_keys($new_user)),
":" . implode(", :", array_keys($new_user))
);
$statement = $connection->prepare($sql);
$statement->execute($new_user);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>
<?php include "templates/header.php"; ?><h2>Add a user</h2>
<form method="post">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname">
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname">
<label for="city">City</label>
<input type="text" name="city" id="city">
<label for="country">Country</label>
<input type="text" name="country" id="country">
<label for="age">Age</label>
<input type="text" name="age" id="age">
<input type="submit" name="submit" value="Submit">
</form>
<a href="index.php">Back to home</a>
<?php include "templates/footer.php"; ?>
When I fill out my form and hit "submit" to write to mysql database, I get the following error:
PHP Notice: Undefined variable: sql in C:\inetpub\wwwroot\create.php on line 35
I am new to both mysql and php and trying to learn the basics using a little project.