我的搜索表单上的SQL准备语句错误

时间:2019-02-27 09:35:11

标签: php sql sql-injection

我发现很难为我的搜索表单编写SQL准备好的语句,我可以得到修复方面的帮助吗?没有SQL准备好的bind语句,一切工作都很好,但是请确保它不是那么安全。

这是我的代码:

<?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";
  }

1 个答案:

答案 0 :(得分: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”子句,因为IVariable直接精确结果将使用直接变量 * /

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

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