我的搜索表单上的SQL Prepared Statement错误

问题描述 投票:0回答:1

我发现很难为我的搜索表单编写SQL预处理语句,我可以获得修复它的帮助吗?没有SQL编写的绑定语句,一切都很好,但我相信它不是那么安全。

这是我的代码:

<?php
  // Define Database connection parameters 
  $dbserver = "localhost";
  $username = "root";
  $password = "";
  $dbname = "student";
  // Lets Connect to theDatabase Table, But if there is an Error lets tell before its too late to figured
  $conn = mysqli_connect ( $dbserver, $username, $password, $dbname ) or die ( ' I can not connect to the database ' );

   // Its time to Capture the varibles and user inpute from the form , also we need to sanitize the input to avoid SQL Injection    
  $study_group = mysqli_real_escape_string ( $conn, $_POST['matric_number']);

  /* Lets try to use bind Statement to reduce further hacking

  I am also avoiding using "LIKE" Clause because IVariable direct Exact results so will be using the Direct Varible 
  */

  $sql = $conn->prepare (" SELECT * FROM study_circle WHERE matric = ? ") ;
  $sql->bind_param('s', $study_group);
  $sql ->execute();

  $results = mysqli_query ($conn, $sql);
  $mysqlResults = mysqli_num_rows ($results);

  if (  $mysqlResults > 0   )
  { 
    while (  $row = mysqli_fetch_assoc ( $results )) 
    {
      // Display results in table form
      echo " <div>
        <h4> ".$row['full_name']."</h4>
      </div>";
     }      
  } else {
    echo " Please Ensure your Matric Number is correct, We can not find anything relting to your data";
  }
php sql sql-injection
1个回答
1
投票

如果你使用预准备语句,你不应该使用mysqli_real_escape_string

尝试注释mysqli_real_escape_string行并直接在bind_param中使用$ _POST ['matric_number']

// $study_group = mysqli_real_escape_string ( $conn, $_POST['matric_number']);

/* Lets try to use bind Statement to reduce further hacking

我也避免使用“LIKE”子句因为变量直接精确结果所以将使用直接变量* /

$sql = $conn->prepare (" SELECT * FROM study_circle WHERE matric = ? ") ;
$sql->bind_param('s',  $_POST['matric_number']);
$sql ->execute();

绑定参数和预准备语句可防止SQL注入,因此您不需要mysqli_real_escape_string操作

© www.soinside.com 2019 - 2024. All rights reserved.