We started working for the first time with PHP
and my SQL
.
There are 2 pages the user can go to:
- The first page that opens had a form with 3 input fields: First name, Last name, your favorite color (hexcode color picker)
- Once you filled in the info, you get send to the 2nd page where the text says "Welcome [first name] [Last name]. Nice to see you. Looks like you also like [color] huh?" and the color of the background changes to the color you have chosen.
I have no issues POST-ing it, but I need to send this info to the SQL database and I cannot seem to figure out what to do next.
index.php
<?php
// server settings
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "bezoeker";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo 'connection succesfull';
}
$name = $_POST['name'];
$lastName = $_POST['lastname'];
$favColor = $_POST['favcolor'];
//add to database
$sql = "INSERT INTO formulier (naam, achternaam, kleur) VALUES ('$name', '$lastName', $favColor)";
//database addition confirmation
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
// Close connection
$conn->close();
include 'template-parts/header.php';
include 'template-parts/main.php';
include 'template-parts/footer.php';
?>
Main.php
<main>
<center>
<form action="welcome.php" method="post">
Naam: <input type="text" name="name"><br>
Achternaam: <input type="text" name="lastname"><br>
Je favoriete kleur: <input type="color" name="favcolor" value="#ff0000">
<input type="submit">
</form>
</center>
</main>
Welcome.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="css/reset.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<title>PHP</title>
</head>
<body>
<div class= "welcome-message">
<h1>Welcome <?php echo $_POST["name"]; ?> <?php echo $_POST["lastname"]; ?> !<br> </h1>
<h2>Leuk dat je er bent!</h2>
<h3>Wouw, mijn favoriete kleur is ook <?php echo $_POST["favcolor"]; ?> !</h3>
<?php echo '<body style="background-color: ' . $_POST['favcolor'] . '">'; ?>
</div>
</body>
</html>
My database Bezoeker
has table called Formulier
with the structure : naam
, achternaam
, kleur
With the current code I get the error
connection succesfullERROR: Could not able to execute INSERT INTO formulier (naam, achternaam, kleur) VALUES ('', '', ). You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
and I cannot figure out what it means or what to do next.