我的代码不起作用,使用PHP Prepared Statements for SQL Injection检查主题名称是否已存在:
代码:
<?php
if($_GET["action"] == "post") {
$servername = "localhost";
$username = "MY DB";
$password = "MY PASS";
$dbname = "MY DB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$checkSubject = $conn->prepare("SELECT * FROM IndexData WHERE SubjectName = ?");
$checkSubject->bind_param('s', $_POST['filename']);
$checkSubject->execute();
$checkSubject->store_result();
$countSubject = $checkSubject->num_rows;
//Create or Edit Files
if(strlen($_POST['filename']) <= 30 && strlen($_POST['filename']) >= 8 && strlen($_POST['comment']) >= 100 && strlen($_POST['comment']) <= 5000 && strlen($_POST['description']) >= 50 && strlen($_POST['description']) <= 500 && strlen($_POST['userSName']) >= 10 && strlen($_POST['userSName']) <= 20) {
if ($countSubject > 0) {
$echoTxt = " <pre>Subject Has Been Posted!
Link: <a href=\"Code-Blog-Index-Posts.php?SubjectName=" . $_POST['filename'] . "\" target=\"_blank\">Click Me</a></pre> <br>";
require("CreateDataPosts.php");
} else {
$echoTxt = die("<pre>[ERROR]Subject Already Exist!</pre>");
}
} else {
echo "<pre><span class=\"error\">Subject must Greater than 8 and Less than 30 characters</span></pre>";
echo "<pre><span class=\"error\">Post must Greater than 100 and Less than 5000 characters</span></pre>";
echo "<pre><span class=\"error\">Description must Greater than 50 and Less than 500 characters</span></pre>";
die();
}
echo $echoTxt;
echo "<a name=\"PostResult\"></a>";
$countSubject->close();
$conn->close();
}
?>
始终返回0
我不知道为什么
我希望你能解决它们!谢谢!
答案 0 :(得分:1)
首先,您要检查是否存在具有相同名称的字段。所以你的查询需要返回0或1。
# IF VALUE = 0 / FIELD NOT FOUND - NO EXISTS
if($countSubject == 0)
{
# the query needs to return 0 to post the new subject, if the returned value is over 0, so exists
$echoTxt = "<pre>Subject Has Been Posted! Link: <a href=\"Code-Blog-Index-Posts.php?SubjectName=" . $_POST['filename'] . "\" target=\"_blank\">Click Me</a></pre> <br>";
require("CreateDataPosts.php");
}
else $echoTxt = die("<pre>[ERROR]Subject Already Exist!</pre>");