dontoften8899 2018-05-09 12: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 12: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部