我是PHP的新手,我被告知我以前的代码可以SQL注入,所以我现在正在尝试解决它。这就是我到目前为止想出的。当我使用以下代码提交到我的表单中时,出现此错误:
注意:未定义的变量:mysqli 在/Applications/XAMPP/xamppfiles/htdocs/index.php 第 49 行
致命错误:在第 49 行的/Applications/XAMPP/xamppfiles/htdocs/index.php 中调用 null 上的成员函数 prepare()。
我已经对第 49 行发表了评论。
<?php
$mysql_pekare= new mysqli ("localhost", "username","pass", "database");
if(!empty($_GET['namn'])) {
$unsafe_variable = "Welcome ". $_GET["namn"]. ". You are ".$_GET["age"]. " years old." ;
$stmt = $mysqli->prepare("INSERT INTO Personinfo(`Personname`, `Personage`) VALUES('$_GET[namn]', '$_GET[age]')");` //this is line 49
$stmt->bind_param("s", $unsafe_variable);
$stmt->execute();
$stmt->close();
$mysqli->close();
}
?>
我的表单如下所示:
<form id="Personinfo" action="index.php" >
<input type="text" id="namn" name="namn" placeholder="namn"/>
<input type="text" id="age" name="age" placeholder="age"/>
<input type="submit"/>
</form>
您首先创建$mysql_pekare
,然后尝试使用$msqli
。那是你的问题。
更改变量以匹配,您应该很好。
$mysql_pekare = new mysqli(...);
$mysql_pekare->prepare(...);
您必须按照命名使用连接:
$mysql_pekare= new mysqli ("localhost", "username","pass", "database");
if(!empty($_GET['namn'])) {
$unsafe_variable = "Welcome ". $_GET["namn"]. " You are ".$_GET["age"]. " years old." ;
$stmt = $mysql_pekare->prepare("INSERT INTO Personinfo(`Personname`, `Personage`) VALUES(?,?))";
$stmt->bind_param("ss", $_GET['namn'], $_GET['age']);
$stmt->execute();
$mysql_pekare->close();
}
一旦你这样做了,你必须为每个不安全的变量使用占位符(?
),然后绑定到这些变量。