我想要的是在查询中使用post变量查询我的数据库.这对我来说不是很有效,有谁知道如何正确地做到这一点?这是我到目前为止所拥有的.
$query = "SELECT column FROM `table` WHERE 'name' = '$_POST[checkname]'";
$result = mysqli_query($db, $query) or die ("no query");
$cod = mysqli_fetch($result);
echo $cod;
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏.多谢你们.
Mysqli支持预处理语句,可防止SQL注入攻击.它看起来像这样:
/* Create a prepared statement */
$stmt = $mysqli -> prepare("SELECT column FROM table WHERE name=?");
/* Bind parameters */
$stmt -> bind_param("s", $_POST['checkname']);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
echo $result;
Run Code Online (Sandbox Code Playgroud)
查看手册以获取更多信息.
快速简要回应评论:
在$stmt->prepare("..."),你正在形成你的查询,你用"?"代替你打算使用的任何变量.
在$stmt -> bind_param(...),您将变量绑定到相应的问号.第一个参数是类型,以下参数是变量.如果您使用的是字符串和整数,则在括号内看起来像"si", $stringVar, $intVar
在$stmt -> bind_result(...)你说明你绑定结果是什么.如果查询是针对名称和年龄的,那么在parethesis内部看起来就像$name, age
在$stmt->fetch(),您正在获取结果.如果它返回了多行,你会做类似的事情:
while($ stmt-> fetch()){// code here}
或者,您可以使用PDO.它看起来像这样:
/* Create a prepared statement */
$stmt = $pdo->prepare("SELECT column FROM table WHERE name=:checkname");
/* Bind parameters */
$stmt->bindParam(':checkname', $_POST['checkname']);
/* Execute it */
$stmt->execute();
/* Fetch results */
$obj = $stmt->fetchObject();
echo $obj->column;
Run Code Online (Sandbox Code Playgroud)
查看手册以获取更多信息.