I am very new to the coding and writing script to insert data from a form. I'd like to check the validations if those are true then data should be submitted to database. The problem is that when the page is loaded, the data has been submitted to the database without click on submit button.
Here is my code:
<?php
include 'config.php';
?>
<html>
<head> <h1 align="center">Credit form </h1>
<script>
function GoToValidation() {
var x = document.forms["insert_form"]["name"].value;
var y = document.forms["insert_form"]["amount"].value;
if (x == null || x == "") {
alert("Name field must be filled out");
return false;
}
if (y == null || y == "") {
alert("Amount field must be filled out");
return false;
}
}
</script>
</head>
<body bgcolor="#D3D3D3">
<table>
<form name="insert_form" action="insert.php" method="post" onsubmit="GoToValidation() ">
<br>
<br>
<br>
<br>
<table align="center" width="30%" border="1" cellpadding="4" cellspacing="0" bordercolor="#ffffff">
<tr>
<td>Name</td>
<td>
<input type="text" name="name">
</td>
</tr>
<tr>
<td>Date</td>
<td>
<input type="text" name="TodayDate">
</td>
</tr>
<tr>
<td>Amount</td>
<td>
<input type="text" name="amount">
</td>
</tr>
<tr>
<td></td>
<td align="right">
<input type="submit" value="submit">
</td>
</tr>
</form>
<?php
$qinsert = "INSERT INTO finance (name,date,amt,status)
VALUES('$_POST[name]','$_POST[TodayDate]','$_POST[amount]','P')";
if (!mysqli_query($con, $qinsert)) {
die('Error: ' . mysqli_error($con));
}
?>
<script>alert ("1 record added") </script>
<?php
mysqli_close($con);
?>
</body>
</html>