PHP Mysql-如果主题名称已经存在,请检查


PHP Mysql - Check Subject Name if already Exist

我的代码不起作用,使用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。

# 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>");