I need to insert data from a HTML form into a database using PHP and MySQLi.
But my code is not working properly. It inserts a few rows of the same data into the table.
I was searching for an answer everywhere but nothing helps. I am new to this so please help me to find the problem. If there is a better way to do something, I would like to see that too.
Thank you.
connect.php:
$link = mysqli_connect("localhost", "root", "", "tutorial");
// Check connection
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
else {
// echo "Connected. ";
}
form.php:
<?php
// Connection
include("connect.php");
?>
<form action="insert.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="firstname" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastName">
</p>
<p>
<label for="Country">Country:</label>
<select name="country_id" id="Country">
<?php
$sql = mysqli_query($link, "SELECT * FROM country");
while ($row = $sql->fetch_assoc()) {
unset($country, $name);
$country = $row['country_id'];
$name = $row['name'];
echo '<option value="'.$country.'">'.$name.'</option>';
}
?>
</select>
</p>
<input type="submit" name="submit" value="Submit">
</form>
insert.php:
<?php
// Connection
include("connect.php");
// Prepare an insert statement
$sql = "INSERT INTO user (country_id, firstname, lastname) VALUES (?,?, ?)";
if ($stmt = mysqli_prepare($link, $sql)) {
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $country, $firstname, $lastname);
// Set the parameters
$country = $_REQUEST['country_id'];
$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
mysqli_stmt_execute($stmt);
// Attempt to execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
echo "Records inserted successfully.";
}
else {
echo "ERROR: Could not execute query: $sql. " . mysqli_error($link);
}
}
else {
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link);
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
?>