簡體   English   中英

PHP 表格插入到 MySQL NULL 允許的值

[英]PHP Form Inserting to MySQL NULL Values Allowed

我有一個提交給 php 文件的表單,該文件將數據插入到 MySQL 中的表中,此表單中有一些字段可能無法填寫,如果是這種情況,即使我設置了記錄也不會插入MySQL 中的字段接受空值

我的代碼

<?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");
?> 

誰能告訴我我需要改變什么來解決這個問題?

最好的

賈斯汀

Ps 抱歉,如果代碼塊有點長,但我認為它與這個問題有關。

您應該更改您的分配(對於可以為空的列),例如

$title = empty( $_POST['inputTitle'] )
 ? 'NULL'
 : "'" . mysql_real_escape_string( $_POST['inputTitle'] ) . "'"
;

在您的查詢中,您必須刪除變量周圍的引號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM