【问题标题】:POST empty fields result in query errorPOST 空字段导致查询错误
【发布时间】:2015-04-04 01:41:53
【问题描述】:

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

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

更新:仅与自动增量列有关的问题

【问题讨论】:

  • 我认为你在$inventoryId,$manufacturer, 上错过了'',比如'$inventoryId','$manufacturer',
  • @RubahMalam db_quote 添加单引号''

标签: php mysql sql forms mysqli


【解决方案1】:
<?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
     }
?>

【讨论】:

  • 不,它不起作用。如果至少有一个空文件,仍然会出现相同的错误。谢谢。
  • 在创建 sql 时尝试使用 sprintf php 函数
猜你喜欢
  • 1970-01-01
  • 2019-08-04
  • 2018-04-15
  • 1970-01-01
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多