Higeath
Higeath

Reputation: 25

Jquery validation checking if value exists in database

As the title says I'm trying to check via jquery validation plugin if value for Patch_No exists. I read through many other similar topics and that's how I figured the code but it seems not to be working although there are no errors. I'm pretty sure DBconnection.php works hence I'm using it in another file to input data.

<?php
include 'DBconnection.php';
$patch = $_REQUEST['patch'];
$sql="SELECT * FROM champions WHERE Patch_No ='$patch'";
$conn->query($sql);
$num = mysql_num_rows($sql);
if($num>0){
    echo 'false';
}
else{
    echo 'true';
}
?>

Here is also the jquery validation code

<script>
    $(document).ready(function(){
        $('#first_form').validate({
            rules: {
                patch: {
                    required: true,
                    minlength: 4,
                    remote: {
                        url: "checkpatch.php",
                        type: "post"
                        }
                    }
                },
            messages: {
                patch: {
                    required: "Please enter patch version.",
                    remote: "This Patch already exists."
                    }

                }
        });
    });
</script>

And last but not least the actual form in php

echo '<form id="first_form" action="index.php" method="POST" style="border: 0; margin: 0;">';
                echo '<input type="hidden" value="'.$formid.'" name="formid">';
                echo '<input type="text" name="patch" placeholder="PATCH e.g. 4.20" required autofocus><br/>';
                echo '<input placeholder="Number of Champions" value="1" type="number" name="champ_number" min="1" max="99" required><br/>';
                echo '<input type="submit" value="next">';
            echo '</form>';

EDIT DBconnection.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "patches";

$conn = new mysqli($servername, $username, $password, $db);
if($conn->connect_error){
    die("Connection failed: ". $conn->connect_error);
}
?>

Upvotes: 0

Views: 2794

Answers (2)

Suchit kumar
Suchit kumar

Reputation: 11859

try like this:

$sql="SELECT * FROM champions WHERE Patch_No ='".$patch."'";
$result = $conn->query($sql);
$num = $result->num_rows;

Upvotes: 1

vaso123
vaso123

Reputation: 12391

These lines are surly bad. You want to fetch a string... Use this:

$sql="SELECT * FROM champions WHERE Patch_No ='$patch'";
$conn->query($sql);
$num = mysql_num_rows($conn);

You need to fetch your $conn, that is the resource, not $sql.

NOTES

  • Do not use mysql functions, they are deprecated.

  • Avoid sql injections by escaping your variables in your query, or use prepared statements.

Upvotes: 0

Related Questions