Using PHP Version 7.1.9, MariaDB 10.1.26.
I'm submitting an array of form data to a MySQL database. The inputs look like this;
// I have removed additional html form code for brevity
<input type="text" name="ip[]">
<input type="text" name="ip[]">
etc...
When inputs are empty, I want to insert a NULL
value into my database, this is where I'm having issues.
I have ensured that my database table is set to;
- allow null = yes
- default - null
My PHP code for handling the form submission is below (please ignore any security vulnerabilities);
// I have removed additional php code for brevity
$arr_ip = $_POST['ip'];
for ($i = 0; $i < count($arr_ip); $i++) {
$arr_ip[$i] = $arr_ip[$i] ? $arr_ip[$i] : 'NULL';
$sql = "INSERT INTO staff (ip) VALUES ( ".$arr_ip[$i]." )
}
The error I receive is;
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax.. ..
When I var_dump($arr_ip)
I get;
array(2) {
[0]=>
string(15) "123.123.123.123"
[1]=>
string(0) ""
}
If I change the PHP to the following (notice the additional ' '
) in the insert, the query runs successfully, two records are inserted but the literal word NULL
is inserted into the database instead of a (NULL)
value.
$arr_ip = $_POST['ip'];
for ($i = 0; $i < count($arr_ip); $i++) {
$arr_ip[$i] = $arr_ip[$i] ? $arr_ip[$i] : 'NULL';
$sql = "INSERT INTO staff (ip) VALUES ( '".$arr_ip[$i]."' )
}
Can someone tell me what I'm doing wrong and how to resolve the issue please, other than using prepared statements?