I try to do something in JS and PHP.
I call a PHP file in Ajax and I want this code to return the count of result lines. So I echo it :
$connexion = new PDO($source, $utilisateur);
$requete = "SELECT * FROM scores WHERE pseudo = '".$_POST['login']."' AND Score >= 0";
$resultat = $connexion->query($requete);
echo ($resultat->rowCount());
And when I attempt to get it in the done in Ajax it doesn't works, it return a fatal error : "Call to a member function rowCount() on a non-object".
$.ajax({
url: "../php/levelState.php",
type: "POST"
}).done(function(levelUnlocked) {
// Affichage de l'écran de sélection
$("#title, #game").hide();
$("link").attr({rel:"stylesheet", href:"../css/select.css"});
$("#select").fadeIn("slow");
for (var i = 0; i < levelUnlocked; i++) {
$('#' + parseInt(levelUnlocked + 1)).removeClass('levelLock').addClass('level');
}
});
});
Thanks for help !
As stated in the PHP documentation
PDO::query() returns a PDOStatement object, or FALSE on failure.
My best guess is that your query is failing and the value of $resultat is FALSE, that's why you cannot run rowCount() method on it.
Your request return null. When you do $resultat->rowCount()
your app produce a Fatal error. You should check if your $resultat
is empty or not.
Anyway, your current query is equal to: "SELECT * FROM scores WHERE pseudo = '' AND Score >= 0";
. That's why you got this error. By the way you should use prepared statement.
To solve your problem, you should specify which data you sent in your ajax function (I've added the keyword data
).
$.ajax({
url: "../php/levelState.php",
data: { login: $("#selector-login").val() } // You should add something like this
type: "POST"
}).done(function(levelUnlocked) {
// Affichage de l'écran de sélection
$("#title, #game").hide();
$("link").attr({rel:"stylesheet", href:"../css/select.css"});
$("#select").fadeIn("slow");
for (var i = 0; i < levelUnlocked; i++) {
$('#' + parseInt(levelUnlocked + 1)).removeClass('levelLock').addClass('level');
}
});
To fix your PHP, I'd do something like this.
header('Content-Type:application/json');
$connexion = new PDO($source, $utilisateur);
$stmt = $connexion->prepare("SELECT COUNT(*) FROM scores WHERE pseudo = ? AND Score >= 0");
$stmt->execute(array($_POST['login']));
$res = $stmt->fetch(PDO::FETCH_NUM);
echo json_encode(array_pop($res));