Reputation: 708
I have a form which submits to a php file which inserts data to a table in MySQL there a some fields in this form which may not be filled in and if this is the case the record doesn't get inserted even though I have set the field in MySQL to accept nulls
My Code
<?php
session_start();
include "includes/connection.php";
$title = $_POST['inputTitle'];
$firstname = $_POST['inputFirstname'];
$lastname = $_POST['inputLastName'];
$address1 = $_POST['inputAddress1'];
$address2 = $_POST['inputAddress2'];
$city = $_POST['inputCity'];
$county = $_POST['inputCounty'];
$postcode = $_POST['inputPostcode'];
$email = $_POST['inputEmail'];
$homephone = $_POST['inputHomephone'];
$mobilephone = $_POST['inputMobilephone'];
$userid = $_POST['inputUserID'];
if($title == '' || $firstname == '' || $lastname == '' || $address1 == '' || $address2 == '' || $city == '' || $county == '' || $postcode == '' || $email == '' || $homephone == '' || $mobilephone == '' || $userid == ''){
$_SESSION['status'] = 'error';
} else {
mysql_query("INSERT INTO contact
(`id`,`user_id`,`title`,`firstname`,`lastname`,`address1`,`address2`,`city`,`county`,`postcode`,`email`,`homephone`,`mobilephone`)
VALUES(NULL,'$userid','$title','$firstname','$lastname','$address1','$address2','$city','$county','$postcode','$email','$homephone','$mobilephone')") or die(mysql_error());
$_SESSION['status'] = 'success';
}
header("location: contacts.php");
?>
can anyone tell me what I need to change to sort this issue out?
Best
Justin
P.s sorry if the code block is a bit long but I think it is relevant in this question.
Upvotes: 0
Views: 1460
Reputation: 13972
You should change your assignement (for the null-able columns), like
$title = empty( $_POST['inputTitle'] )
? 'NULL'
: "'" . mysql_real_escape_string( $_POST['inputTitle'] ) . "'"
;
And in your query you have to remove the quotes around the variables.
Upvotes: 2