简体   繁体   English

我的mysqli代码出了什么问题?

[英]What is wrong with my mysqli code?

I am trying to embed mysqli code into my web page so I can eliminate sql injection. 我试图将mysqli代码嵌入到我的网页中,以便消除SQL注入。 Here is what my code looks like right now: 这是我的代码现在的样子:

$gYear = $_POST["year"];
$gYear2 = $_POST["year2"];
$gMonth = $_POST["month"];
$gSelect = $_POST["location"];

$query = $conn->prepare("SELECT $gSelect, Year FROM unemployed WHERE year BETWEEN '$gYear' AND '$gYear2' and month='$gMonth'");
$query->bind_param('ssss', $gyear, $gYear2, $gMonth, $gSelect);

$query->execute(); 
$result = $query->get_result();

while ($row = $result->fetch_object()){


// do something with gathered rows 
}

Now, once the form is submitted, I get two errors. 现在,提交表单后,我得到两个错误。 Here is what they say: 他们说的是:

Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of variables doesn't match number of parameters in prepared statement in

AND

Fatal error: Call to undefined method mysqli_stmt::get_result() in

I really don't know what my issue is. 我真的不知道我的问题是什么。 I tried to follow the rules listed in How can I prevent SQL injection in PHP? 我尝试遵循如何防止PHP中的SQL注入中列出的规则 . Does anyone know what my issues are? 有谁知道我的问题是什么? Why am I receiving these two error messages? 为什么会收到这两个错误消息? Any help would be greatly appreciated. 任何帮助将不胜感激。

For mysqli::prepare() , you must use ? 对于mysqli::prepare() ,必须使用? for parameters. 用于参数。 (The code in the post uses standard PHP variable substitution into the string - this should not be done for values when using placeholders.) (文章中的代码在字符串中使用了标准的PHP 变量替换 -使用占位符时,不应对值进行此操作。)

I'd strongly advise against letting users choose the column that you're selecting. 强烈建议您不要让用户选择您要选择的列。 Use a switch() or something similar to choose the column name in code, and place it in the $column variable. 使用switch()或类似的方法在代码中选择列名称,并将其放置在$ column变量中。

switch($_POST['location']){
  case "loc1":
    $column = "location_one";
    break;
  case "loc2":
    $column = "location_two";
    break;
  // etc, etc...
}
$query = $conn->prepare("SELECT $column, year FROM unemployed WHERE year BETWEEN ? AND ? and month=?");
$query->bind_param('sss', $gyear, $gYear2, $gMonth);

You Can use PDO to prevent sql injection and it is also work for >= PHP 5.1 您可以使用PDO防止SQL注入,它也适用于> = PHP 5.1

PDO and the PDO_SQLITE driver is enabled by default as of PHP 5.1.0. You may need to
enable the PDO driver for your database of choice;consult the documentation for 
database-specific PDO drivers to find out more about that.

PDO documentation PDO文档

It is most widely used and if you know how to use mysqli then is it also easy for you 它使用最广泛,如果您知道如何使用mysqli,那么对您来说也很容易

Tutorial from tutsplus tutsplus的教程

Why you Should be using PHP's PDO for Database Access 为什么要使用PHP的PDO进行数据库访问

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM