Question

I make this code to show in live if the users license is already in DB, the code works in half.. only show the error if is alredy in DB but when the license isn't not show me nothing.. can you see where is my error and if this code is safe from sql injection?

code:

<?php
    sleep(1);
    include('connection.php');
    if($_REQUEST)
    {
        try {
            $stmt = $conn->prepare('SELECT license FROM users_lic WHERE license = ?');
            $stmt->bindParam(1, $_REQUEST['license']); 
            $stmt->execute();
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

                if($row['license'] > 0) // not available
                {
                    echo '<div id="Error">The license is already in our system</div>';
                }
                else 
                {
                    echo '<div id="Success">The license does not exist in our system</div>';
                }
            }
        }
        catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }
    }
?>

The JS:

$(document).ready(function() {  
    $('#lic').blur(function(){
        $('#Info_lic').html('<img src="img/loaders/loader.gif" alt="loader" />').fadeOut(1000);
        var license = $(this).val();        
        var dataString = 'license='+license;
        $.ajax({
            type: "POST",
            url: "includes/val_lic.php",
            data: dataString,
            success: function(data) {
                $('#Info_lic').fadeIn(1000).html(data);
                //alert(data);
            }
        });
    });              
}); 

the part of license form:

<div class="span4">
    <label><b>License : </b></label><input type="text" class="input-block-level" id="lic" name="license" />
    <div id="Info_lic"></div>
</div>
Was it helpful?

Solution

Put your row checking outside of your while loop and I have changed if($row['license'] > 0) to if($stmt->rowCount() > 0)

Give this a try now. (Tested on my server)

<?php
    sleep(1);
    include('connection.php');
    if($_REQUEST)
    {
        try {
            $stmt = $conn->prepare('SELECT license FROM users_lic WHERE license = ?');
            $stmt->bindParam(1, $_REQUEST['license']); 
            $stmt->execute();
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            }
        }
        catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }

if($stmt->rowCount() > 0)

    {
        echo '<div id="Error">The license is already in our system</div>';
    }
    else 
    {
        echo '<div id="Success">The license does not exist in our system</div>';
    }

}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top