I have a bit of an issue getting jQuery Validation to check if an email address already exists in a mysql table.
Every time I submit the form, it tells me the email already exists, even though I know it doesn't.
Here's the code I have:
validation.js
$(document).ready(function () {
$('#signup').validate({
errorLabelContainer: "#cs-error-note",
wrapper: "li",
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-username.php",
type: "post"
}
}
},
messages: {
email: {
required: "Please enter your email address.",
email: "Please enter a valid email address.",
remote: "Email already in use!"
}
},
submitHandler: function(form) {
form.submit();
}
});
});
check-username.php
<?php
require('../../private_html/db_connection/connection.php');
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$query = $conn->prepare("SELECT * FROM 'user_accounts' WHERE email = '" . $_POST['email'] . "'");
$query->execute();
if( $query->rowCount() > 0 ){
echo 'true';
}
else{
echo 'false';
}
?>
Your help is much appreciated!
You have to change the row count if / else condition in query
Script
HTML
PHP
Warning Do not use this PHP code reason
rowCount()
may not work so skip it and jump to code at bottom of answer.Edit: As @Jay Blanchard very consistent and dead sure that above code will not work
rowCount() doesn't work for SELECT statements. stackoverflow.com/a/31569733/1011527
Nope, this will not work because rowCount() doesn't work for SELECT statements. You're not getting a row count at all.
Try echoing $query->rowCount() and you'll see the issue
and makes me wonder How the above code is working on my live server when It shouldn't so I done some digging and found this;
and this
Source of Above statements php.net manuals
In both above statements, some databases and For most databases
rowCount()
does work but on other-handAs OP only wants the count of rows and not all the data of all the rows so can be also done like this. Credit goes to @Jay Blanchard
Use This Code Example
made some changes in PHP, use
isset
function.See in Action
rowCount()
will not work in the situation. From the docs:Note that it doesn't return anything for a SELECT statement. To get the row count in your code you would do this:
In order to avoid the possibility of SQL Injection Attack I use a prepared statement, sending an array (of one) containing the values to be used in the query in the
execute()
statement.