I am trying to add data into a MySql Database using PHP.
The code:
<?php
session_start();
include('config.php');
if(isset($_POST['Submit'])) {
$city = $_POST['city'];
$from_station = $_POST['from_station'];
$from_date = $_POST['from_date'];
// Prepare and execute the SQL query
$sql = "INSERT INTO journeys (city, from_station, from_date) VALUES ('$city', '$from_station', '$from_date')";
$result = $conn->query($sql);
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
<!DOCTYPE html>
<html lang="pt_PT">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IR PLANNER</title>
<link rel="stylesheet" href="Stylesgeneral_styles.css">
<link rel="stylesheet" href="Stylescitymanager_styles.css">
</head>
<body>
<form class="modal" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<label for="city">City:</label>
<input type="text" name="city" id="city">
<label for="from_station">From Station:</label>
<input type="text" name="from_station" id="from_station">
<label for="from_date">From Date:</label>
<input type="date" name="from_date" id="from_date">
<input type="submit" value="Submit" id="Submit">
</form>
</body>
</html>
When the submit button is pressed no error is displayed. However, when the database table is checked nothing appears.
I have read articles and the sql connection (config.php) is working perfectly (in other pages and files is working) and the sql query is also good.
Is anyone facing this problem?
2
Answers
You need to pass name attribute in submit button untill that you are not getting any value from that.Which always return false in your condition.So nothing will update nor error generate.Just update that here is updated code.
There are a few things that you could do to analyse the problem/ optimize the code.
1. To debug your code: echo a value to check if you get inside the if statement
For example:
Now run the code to see which lines are reached.
2. Your code inside the if statement is not executed, because:
This code:
Needs a
name
-attribute, in order to be send as data to the server:3. Use mysqli prepare to prepare the sql statement
Instead of your current insert code, make it
In this way no SQL injection could occur.
4. In your code you also executed the SQL twice.
On these lines:
Replace with the code at point 3.
The resulting code