[英]PHP Form Inserting to MySQL NULL Values Allowed
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我有一个提交给 php 文件的表单,该文件将数据插入到 MySQL 中的表中,此表单中有一些字段可能无法填写,如果是这种情况,即使我设置了记录也不会插入MySQL 中的字段接受空值
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贾斯汀
Ps sorry if the code block is a bit long but I think it is relevant in this question. Ps 抱歉,如果代码块有点长,但我认为它与这个问题有关。
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.在您的查询中,您必须删除变量周围的引号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.