POST空字段会导致查询错误

时间:2015-02-04 13:46:50

标签: php mysql sql forms mysqli

我有一个包含某些字段的表单

<form action="add.php" method="post">
/*Some fields*/
</form>

我还创建了以下函数来引用和转义表单提交的值

<?php
    // Quote and escape form submitted values
    function db_quote($value) {
        $connection = db_connect();//Connection with database "NO ISSUE HERE"
        return "'" . mysqli_real_escape_string($connection,$value) . "'";//Maybe the issue here
     }
?>

然后我将值传递给函数,如下所示

$inventoryId = db_quote($_POST['inventoryId']);
$sn = db_quote($_POST['sn']);
$model = db_quote($_POST['model']);
//etc...

如果我填写所有字段,每件事都可以正常工作,但如果至少有一个空字段,即用户输入的值没有,我会收到以下错误

Catchable fatal error: Object of class mysqli could not be converted to string in etc...

这是我试图运行的查询

<?php
    $sql = "INSERT INTO inventory (id,manufacturer_id,supplier_id,servicer_id,operator_id,sn,model,inventory_name,inventory_type,description,power,purchase_order,purchase_cost,arrival_date,installation_date,warranty_date,incident_history,conditions,m_next_date,m_start_date,m_deadline,lifetime,inspection_frequency,location,purchased_from)
    VALUES ($inventoryId,$manufacturer,$supplier,$servicesId,$operatorId,$sn,$model,$inventoryName,$inventorType,$description,$power,$purchaseOrder,$purchaseCost,$arrivalDate,$installationDate,$warranty,$incident,$conditions,$nextDate,$startDate,$deadline,$lifetime,$inspection,$location,$purchasedFrom);";

    if ($connection->query($sql) === TRUE) {
        echo "<p>New inventory ".$inventoryId." created successfully</p>";
    } else {
    echo "Error: " . $sql . "<br>" . $connection;
    }
    $connection->close();
?>

更新:仅限自动增量列的问题

1 个答案:

答案 0 :(得分:0)

<?php
    // Quote and escape form submitted values
    function db_quote($value) {
        $connection = db_connect();//Connection with database "NO ISSUE HERE"
        return "'" . mysqli_real_escape_string($connection,$value) . "'";//Maybe the issue here
     }
?>

将其转换为

<?php
    // Quote and escape form submitted values
    function db_quote($value) {
        if(!$value) return '';
        $connection = db_connect();//Connection with database "NO ISSUE HERE"
        return "'" . mysqli_real_escape_string($connection,$value) . "'";//Maybe the issue here
     }
?>