dontoften8899 2018-05-09 20:50
浏览 45
已采纳

PHP:针对数据库表的Textarea输入验证

I am attempting to validate a textarea input against a database table. If any of the entries exists, the form is rejected. If no entry is found, then form is accepted and textarea input entered into the database table with each linebreak going to a new row.

I am having trouble though, the following script seems to skip the validation portion and goes straight to just adding the textarea input into the database.

<?php
if (isset($_GET["submit"])) {
}

$host = "localhost";
$user = "root";
$password = "password";
$database = "test";
// Establish server connection and select database
$dbh = mysqli_connect($host, $user, $password, $database);
  if (mysqli_connect_errno()) {
  die('Unable to connect to database ' . mysqli_connect_error());
  }
  else {
      $text = trim($_POST['serial']);
      $textAr = explode("
", $text);
      $textAr = array_filter($textAr, 'trim'); // remove any extra  chars
      foreach ($textAr as $line) {
               $query = mysqli_query($dbh, "SELECT serials FROM `wp27_test6serial` WHERE `serials` = '$line'");
               $result = mysqli_query($dbh, $query);
           if (mysqli_num_rows($result) > 0) {
                     die('entry already exists');
            }
           else {
                     $query = mysqli_query($dbh, "INSERT INTO wp27_test6serial (rtxserials) VALUES ('$line')");
                     echo ('serials submitted');
                }
            }
   }

Can anyone tell me what is wrong with the script and why it is not validating before moving onto inserting the textarea string into the database?

Thank you

  • 写回答

1条回答 默认 最新

  • duanmeng3573 2018-05-09 20:53
    关注

    You are querying twice.

    $query = mysqli_query($dbh, "SELECT serials FROM `wp27_test6serial` WHERE `serials` = '$line'");
    

    Should be

    $query = "SELECT serials FROM `wp27_test6serial` WHERE `serials` = '$line'";
    

    And your code is vunerable to SQL Injection attack. Use prepared statements.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看