简体   繁体   中英

PHP Mysql - Check Subject Name if already Exist

My code doesn't work, Checking if Subject Name is already exist using PHP Prepared Statements for SQL Injection:

Code:

<?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();
}
?>

It Always Return to 0
I don't know why but I Hope You can solve it guys!, Thanks!

First you are checking if there is a field with the same name. So your query needs to return 0 or 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>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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