I’m inserting date from a form using PHP. I have 24 fields in which a user can insert in data into the database. The Problem is how do I not allow empty fields from becoming rows in MySQL is they are left empty from the User? None of the fields are required and fields are formatted as input text fields. What I was considered using is in if statement in the values section once queried; here’s an example:
/**************
* HTML Form
**************/
<form action='insert.php' method='post'>
<p> What items do you have for sale?</p>
Item 1: <input type='text' name='item1'> Price: <input type='text' name='item1cost'>
Item 2: <input type='text' name='item2'> Price: <input type='text' name='item2cost'>
Item 3: <input type='text' name='item3'> Price: <input type='text' name='item3cost'>
<input type="submit" name="Submit" value="Submit">
</form>
/**************
* PHP
**************/
$user = (from $_SESSION)
$item1 = $_POST['item1'];
$item1cost = $_POST['item1cost'];
$item2 = $_POST['item2'];
$item2cost = $_POST['item2cost'];
$item3 = $_POST['item3'];
$item3cost = $_POST['item3cost'];
/*********************
* MySQL INSERT query
*********************/
$query = "INSERT INTO monthly_expenses (`userid`, `item`, `amount`)"
. "VALUES ($user,'$item1', '$item1cost'),
($user,'$item2', '$item2cost'),
($user,'$item3', '$item3cost'),
If user leaves either one of the fields blank how can I get them not to insert into the database so there’s not an empty row with just the userid?
You can put values into array, then check if they are empty or not (maybe some other checks would be recomended concerning security issues) and create $values variable, which you can load into database.
It would be also possible to give HTML input field name’s as arrays like item[] and parse them straight to php-arrays.