I am using a form to insert data to my database. I have a textbox with the ID and NAME name1
.
If the user clicks on submit the PHP script sends the data to my database. But the insert statement is also executed when the textbox is empty. If there is no data entered the script creates an empty row in the database.
In my PHP script I want to check if the (value) in the textbox is empty or not.
I have tried multiple codes but the script still sends the empty data to my database.
Does someone know how I can check if there is data entered in the textbox.
Here is my script:
$query1 = "INSERT INTO product(user_id, name, price, tax) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query1);
$exec1 = $stmt->execute(array($_SESSION['USER_ID'], $name1, $price1, $tax1));
if($exec1){
echo '<p>product1 is created</p>';
} else {
echo '<p>error</p>';
}
It looks like that you are not checking if the text field is empty. Please try this:
if(!empty($_POST['name1'])) {
$query1 = "INSERT INTO product(user_id, name, price, tax) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query1);
$exec1 = $stmt->execute(array($_SESSION['USER_ID'], $name1, $price1, $tax1));
if($exec1){
echo '<p>product1 is created</p>';
} else {
echo '<p>error</p>';
}
}
check if a field is empty in order to return an error or a message just do this (brief example):
if (!(empty($_POST['textbox']))){
execute some code....
}
else {
execute some code...
}