【问题标题】:How to insert Integer value in DB - PHP如何在数据库中插入整数值 - PHP
【发布时间】:2014-04-07 08:50:10
【问题描述】:

我使用 PHP 在数据库中插入整数值。

我是这样使用的

$postcode = $_POST['postcode'];
$mysql_user_resultset = mysqli_query($con, "INSERT into user (postcode) VALUES ($postcode)");

我在数据库中有几个字段。像姓名,用户名等都定义为varchar,但邮政编码只定义为int。如果不输入邮政编码的值,则不会插入数据库

【问题讨论】:

  • 可以在插入前加一个var_dump($postcode)吗?
  • 从您的示例中:$postcode = isset($_POST['postcode'])?$_POST['postcode']:0;,因此如果未设置邮政编码,它将被设置为 0。此外,您应该转义您传递的参数
  • 您可以使用intvalis_numeric 使您的邮政编码为整数。
  • @Prasanth is_numeric确保某些东西是整数;它支持各种格式,例如'0.1e-05'。要仅检查数字,您需要 ctype_digit()
  • 您对此有何疑问?为什么不先检查要输入的数据,然后然后插入呢?

标签: php


【解决方案1】:

您可以简单地将变量转换为 int:

$postcode = (int) $_POST['postcode'];
$mysql_user_resultset = mysqli_query($con, "INSERT into user (postcode) VALUES ($postcode)");

请注意,您没有使用任何有关 SQL 注入的预防措施,我建议您在查询参数之前绑定参数,using PDO class

【讨论】:

    【解决方案2】:

    $_POST['postcode'] 转换为int,使用

    $postcode = (int)$_POST['postcode'];
    

    【讨论】:

      【解决方案3】:

      使用 PDO 或 sprintf 格式化 mysql 查询:

      sprintf 示例:

      $mysql_user_resultset = mysqli_query($con, sprintf(
        "INSERT into user (postcode) VALUES (%d)", 
      $_POST['postcode']));
      

      PDOexample:

      $st = $db->prepare("INSERT into vendors user (postcode) VALUES (:postcode)");
      $st->bindParam(':postcode', $_POST['postcode'], PDO::PARAM_INT);
      $mysql_user_resultset = $st->execute();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-09
        • 2021-10-06
        相关资源
        最近更新 更多