简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM