I've tried to verify if an email already exists in the database.
The same system worked perfectly if I tried to verify a username.
I'm using AJAX and PHP.
This is the file that gets the $_POST variables.
<?php
require_once 'Config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST['email'];
$password = $_POST['password'];
if (!empty($password) and !empty($email)) {
$notEmpty = true;
include 'validate.php';
if($notEmpty == true and validateEmail($email) == true){
$password = md5($password);
$stmt = $link->prepare("INSERT INTO `Users`(`user_password`, `user_email`) VALUES (?,?)");
$stmt->bind_param("ss",$email,$password);
$stmt->execute();
}
}else{
$notEmpty == false;
}
}
?>
and this is the file that verifies the email doesn't exist on the database.
function validateEmail($user_email){
include '../Backend/Config.php';
$sql = "SELECT `user_password`, `user_email` FROM `Users` WHERE `user_email` = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("s",$user_email);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$row = $result->fetch_assoc();
if ($result->num_rows > 0) {
echo 1;
return false;
}
else{
// echo json_encode(array('status' => 'OK'));
echo 0;
return true;
}
}
Js code(ajax):
$('#form').submit(function(e) {
//Don't refresh the page
e.preventDefault();
//Collecting data for the server call
post_data = {
'email' : $('input[name=email]').val(),
'password': $('input[name=password]').val()
};
//AJAX server call to signup.php,which calls validate.php
$.ajax({
method: "POST",
url: "../Backend/signup.php",
data: post_data
})
//Server response and setting the input values to ""
.then(function( msg ) {
if(msg == 0){
console.log("Success, user data inserted. Code: " + msg);
}
//Failed
if(msg == 1){
console.log("Inserting failed. Error code:" + msg);
document.getElementById("error").innerHTML = "This email already exists.";
}
$('input[name=email]').val("");
$('input[name=password]').val("");
});
});
It inserts it anyway, what is the problem here?
If you immediately call num_rows() after executing a prepared statement, it will usually return 0 as it has no way to know how many rows are in the result set, since the result set is not saved in memory yet. You must first call store_result() to buffer the results so that the subsequent call to num_rows() will contain the correct results.
This is explained in the "User Notes" section at the bottom of the PHP documentation for num_rows().
I've been trying to grab a username based on registered email when user enters his email and click on a button I've provide two data to my ajax request first is [cf] which identify which portion of code should be processed and second is the email but when clicking the button nothing happens and no errors appear in the console only when I open the page that have the php code of ajax request it says "Notice: Undefined variable: funcCall in D:\XAMPP\htdocs\lahj\framework\signin.php on line 19"
Here I will provide my code for ajax:
$("#login-next-btn").click(function(){
if(!$("#signin-email").val().trim()){
var email = $("#signin-email").val().trim();
$.ajax({
url: "framework/signin.php",
type: "POST",
data: {cf:'cf1',email:email},
dataType:"json",
success: function(data){
if(data.result != "0")
{
alert("helo");
$("#signin-box-header p:first-of-type").text("مرحبًا");
$("#signin-box-header p:last-of-type").remove();
$("#signin-box-header").append("<p id='sigin-email-display'>"+data.result+"</p>");
$("#first-loader").fadeOut(600,function(){
$("#second-loader").css({"display":"flex"}).fadeIn(400);
});
}
else
{
alert("fail");
}
}
});
}
});
and here is my php code in a file called signin.php in a folder called framework:
<?php
ini_set( 'error_reporting', E_ALL );
ini_set( 'display_errors', true );
include_once 'db.php';
$email = null;
$funcCall = null;
if(isset($_POST['email']))
{
$email = $_POST['email'];
}
if(isset($_POST['cf']))
{
$funcCall = $_POST['cf'];
}
if($funcCall == 'cf1' && !empty($email))
{
try
{
$database = new db();
$db = $database->openConnection();
$stmt = $db->prepare("select userName from khUsers where email = ?");
$stmt->execute(array($email));
$usersName = $stmt->fetchColumn();
$data = array('result' => $usersName);
echo json_encode($data);
}
catch (PDOException $e)
{
echo "There is some problem in connection: " . $e->getMessage();
$data = array('result' => "0");
echo json_encode($data);
}
}
?>
Add exit() function at the end of json_encode() function. it will show you result/error on your request in console.
if($funcCall == 'cf1' && !empty($email))
{
try
{
$database = new db();
$db = $database->openConnection();
$stmt = $db->prepare("select userName from khUsers where email = ?");
$stmt->execute(array($email));
$usersName = $stmt->fetchColumn();
$data = array('result' => $usersName);
echo json_encode($data); exit();
}
catch (PDOException $e)
{
echo "There is some problem in connection: " . $e->getMessage();
$data = array('result' => "0");
echo json_encode($data); exit();
}
}
I'm making a simple login test and the code returns the json response when the fields are empty,but not when the login fails or succeds, like:
Empty Fields - OK
Login Succeded - nope
Login failed - nope
Request:
var loader = $('#trabalhando');
$(function() {
$('form').submit(function(e) {
loader.fadeIn("slow");
e.preventDefault();
$.ajax({
url: 'login.php',
data: $(this).serialize(),
method: 'post',
dataType: 'JSON',
success: function(data){
loader.fadeOut("slow");
console.log(data);
alert(data.resp);
},
error: function(data) {
alert(':(');
loader.fadeOut("slow");
console.log(data);
}
});
});
});
Response:
<?php
header('Content-Type: application/json');
if (isset($_POST['cpf']) && isset($_POST['pass']) && $_POST['cpf'] != "" && $_POST['pass'] != "") {
$cpf = $_POST['cpf'];
$passw = sha1(strrev(md5($_POST['pass'])));
include 'config.php';
$sql = "SELECT * FROM users WHERE cpf = :cp AND passwd = :pw";
$chec = $db->prepare($sql);
$chec->bindParam('cp', $cpf, PDO::PARAM_STR);
$chec->bindParam('pw', $passw, PDO::PARAM_STR);
$chec->execute();
if ($chec->rowCount() > 0) {
echo json_encode(array('resp' => 'nice'));
} else {
echo json_encode(array('resp' => 'nope'));
}
} else {
echo json_encode(array('resp' => 'fields'));
}
?>
Edit: updated the code
You are not binding your parameters properly, so you probably have a PDO error that you're not handling. Change:
$chec->bindParam('cp', $cpf, PDO::PARAM_STR);
$chec->bindParam('pw', $passw, PDO::PARAM_STR);
To:
// notice the colon : in front of var names, so it matches the placeholders!
$chec->bindParam(':cp', $cpf, PDO::PARAM_STR);
$chec->bindParam(':pw', $passw, PDO::PARAM_STR);
In general, database, file and remote server operations (FTP, HTTP, SSH...) are very finicky so when you rely on these, always error check! You should factor out your queries into a specialized function that does proper error checking.
/**
* #param PDO $db The PDO object with which to perform queries
* #param string $sql raw SQL (eg: "select * from t where a = :param" )
* #param array $params Array of parameter names and values eg: [':param' => 'value']
* #param string $error Will be filled with the error details if the DB operations fail
* #return false|PDOStatement FALSE on error, or the statement on success
*/
function query(PDO $db, $sql, array $params, &$error){
try{
// error check every step!
if(!$stmt = $db->prepare($sql)) throw new Exception($db->errorInfo()[2]);
if(!$stmt->execute($params)) throw new Exception($stmt->errorInfo()[2]);
return $stmt; // return the $stmt for further processing
}catch (Exception $e){
$error = $e->getMessage();
return false;
}
}
Now you can perform your queries much more simply:
$stmt = query($db, $sql, $params, $error);
// decide what to do on failure
if(!$stmt) die($error);
// now it's safe to use $stmt to fetch results, count rows...
Update
You said:
the fail is exactaly the same as the success, loader out and alert, but this time with a sad face on the alert
That's expected. success in the Ajax call just means that the server responded normally. It doesn't say anything about what is inside the json string. If you want to trigger the error Ajax callback, your server will need to set an error HTTP response code like this:
http_response_code(401);
echo json_encode(array('resp' => 'nope'));
Update 2
To find out the details of the error triggered by the Ajax call, modify the callback and examine the results:
error: function(jqXHR, textStatus, errorThrown){
console.log('textStatus: ' + textStatus);
console.log('errorThrown: ' + errorThrown);
}
Maybe your server is sending other content along with the JSON that is corrupting the output. Try closing the buffer at the top of your script, and exiting immediately with your echo:
<?php
ob_end_clean(); // at top of script
//try echoing this way
die(json_encode(array('resp' => 'nice')));
die(json_encode(array('resp' => 'nope')));
It would seem like there is either a problem in your config.php file, or with your sql statement
try putting your code into a try catch, and then returning the error as json:
<?php
header('Content-Type: application/json');
if (isset($_POST['cpf']) && isset($_POST['pass']) && $_POST['cpf'] != "" && $_POST['pass'] != "")
{
$cpf = $_POST['cpf'];
$passw = sha1(strrev(md5($_POST['pass'])));
try
{
include 'config.php';
$sql = "SELECT * FROM users WHERE cpf = :cp AND passwd = :pw";
$chec = $db->prepare($sql);
$chec->bindParam(':cp', $cpf, PDO::PARAM_STR);
$chec->bindParam(':pw', $passw, PDO::PARAM_STR);
$chec->execute();
if ($chec->rowCount() > 0)
{
echo json_encode(array('resp' => 'nice'));
}
else
{
echo json_encode(array('resp' => 'nope'));
}
}
catch(Exception $e)
{
echo json_encode($e->getMessage());
}
}
else
{
echo json_encode(array('resp' => 'fields'));
}
?>
Edit: incorporates #BeetleJuice's fix
im using the function PDO::lastInsertID (also happening with mysqli_insert_id), but it's always returning 0.
I already looked up the problem and saw that this should've fixed the problem: MySQL: LAST_INSERT_ID() returns 0
by turning on persistentConnections in the phpmyadmin "config.inc.php" file, but the problem still remains...
my table 'reservations' has a primary key which AUTO_INCREMENTs.
here is my code:
I got a button on my site which calls this javascript code:
function sonderbuchung()
{
setReservationType();
getSonderbuchungID();
}
function getSonderbuchungID() {
$.ajax({
url:'sonderbuchungEditID.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
function setReservationType()
{
$.ajax({
url: "reservationType.php",
type: "POST",
data: 'reservationtype=sonderbuchung',
success: function(data) {
$('#output').html(data);
},
error: function(data) {
$('#output').html(data.responseText)
},
});
}
On my mySQL server there is a random String generated after a Insert happend, and now I want to get the random String by looking at the last Inserted ID and taking it's randomString. (Not implemented yet obviously 'cause of this problem)
sonderbuchungEditID.php:
<?php
require_once('bdd.php'); //Database connection
echo($bdd->lastInsertID());
?>
reservationType.php (all fine working, just for the sake of all code)
<?php
require_once('bdd.php');
if(isset($_POST['reservationtype'])){
$reservationtype = $_POST['reservationtype'];
$sql = "INSERT INTO reservations(reservationtype) values ('$reservationtype')";
$query = $bdd->prepare($sql);
if ($query == false) {
file_put_contents('LOGname.txt', print_r($bdd->errorInfo(), true));
die ('Error prepairing');
}
$sth = $query->execute();
if ($sth == false) {
file_put_contents('LOGname.txt', print_r($query->errorInfo(), true));
die ('Error executing');
}
}
?>
You would need to capture and store the ID when the row is inserted.
sonderbuchungEditID.php:
<?php
echo isset($_SESSION['last_id']) ? $_SESSION['last_id'] : "-1";
?>
reservationType.php:
<?php
require_once('bdd.php');
if(isset($_POST['reservationtype'])){
$reservationtype = $_POST['reservationtype'];
$sql = "INSERT INTO reservations(reservationtype) values ('$reservationtype')";
$query = $bdd->prepare($sql);
if ($query == false) {
file_put_contents('LOGname.txt', print_r($bdd->errorInfo(), true));
die ('Error prepairing');
}
$sth = $query->execute();
if ($sth == false) {
file_put_contents('LOGname.txt', print_r($query->errorInfo(), true));
die ('Error executing');
} else {
// Remember the last ID inserted.
$_SESSION['last_id'] = $bdd->lastInsertID();
}
}
?>
My ajax:
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//$(".the-return").html("<br />JSON: " + data["json"] );
// alert("Form submitted successfully.\nReturned json: " + data["json"]);
alert(data);
// window.location='success.php'
}
});
return false;
});
});
I declared a variable to store unique_id like this:
$unique_id=uniqid();
I'm inserting data like this:
try
{
$stmt2 = $pdo->prepare('INSERT INTO usrinfo (UUID,Name,Phone,Email,Postcode,DateReg,Reputation,ReviewPlus,ReviewNeg,Sex,Status,IsTuitionCentre) VALUES(:uuid,:name,:phone,:email,:poscode,now(),:reputation,:reviewplus,:reviewneg,:sex,:status,:permission)');
$stmt2->execute(array(
':uuid' => $unique_id,
':name'=>$name,
':phone'=>$phone,
':email'=>$email,
':poscode'=>$postcode,
':reputation'=>78,
':reviewplus'=>65,
':reviewneg'=>3,
':sex'=>$gender,
':status'=>0,
':permission'=>$permission
));
# Affected Rows?
echo $stmt2->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
Now, I want to pass the above unique_id to ajax page but couldn't.
echo $unique_id;
It just doesn't alert anyting, but:
$abc="123";
echo $abc;
this shows the alert box with value 123!
Why is it so? WHy I coudn't pass unique_id value like this?
MY ENTIRE PHP SCRIPT:
<?php
//Function to check if the request is an AJAX request
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
$return = $_POST;
$return["json"] = json_encode($return);
//below code to store in database
$data = json_decode($return["json"], true);
/*....salting starts........*/
/*..........salting ends..............*/
echo $unique_id=uniqid();
$name=$data['name'];
$phone=$data['phone'];
$email=$data['email'];
$postcode=$data['postcode'];
$a=$data['sub'];
$b=$data['rate2'];
$subject_rate = array_intersect_key($b,$a);
/*...pdo.............................*/
$username="root";
$password="";
try {
//$pdo = new PDO('mysql:host=localhost;dbname=users', $username, $password);
//$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
$stmt = $pdo->prepare('INSERT INTO authsessions (email,useruuid,salt,hashpword) VALUES(:email,:useruuid,:salt,:hash)');
$stmt->execute(array(
':email' => $email,
':useruuid'=>$unique_id,
':salt'=>$salt,
':hash'=>$hash
));
# Affected Rows?
$stmt->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
//query2
try
{
$stmt2 = $pdo->prepare('INSERT INTO usrinfo (UUID,Name,Phone,Email,Postcode,DateReg,Reputation,ReviewPlus,ReviewNeg,Sex,Status,IsTuitionCentre) VALUES(:uuid,:name,:phone,:email,:poscode,now(),:reputation,:reviewplus,:reviewneg,:sex,:status,:permission)');
$stmt2->execute(array(
':uuid' => $unique_id,
':name'=>$name,
':phone'=>$phone,
':email'=>$email,
':poscode'=>$postcode,
':reputation'=>78,
':reviewplus'=>65,
':reviewneg'=>3,
':sex'=>$gender,
':status'=>0,
':permission'=>$permission
));
# Affected Rows?
$stmt2->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
//query3
try
{
$stmt3 = $pdo->prepare('INSERT INTO tutoravailability (uuid,week_morning,week_afternoon,week_evening,weekend_morning,weekend_afternoon,weekend_evening) VALUES(:uuid,:week_morning,:week_afternoon,:week_evening,:weekend_morning,:weekend_afternoon,:weekend_evening)');
$stmt3->execute(array(
':uuid' => $unique_id,
':week_morning'=>$week_morning,
':week_afternoon'=>$week_afternoon,
':week_evening'=>$week_evening,
':weekend_morning'=>$weekend_morning,
':weekend_afternoon'=>$weekend_afternoon,
':weekend_evening'=>$weekend_evening
));
# Affected Rows?
$stmt3->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
//query4
foreach($subject_rate as $v=>$k)
{
$key=$v;
$value=$k;
$post_unique_id= uniqid();
try
{
$stmt4 = $pdo->prepare('INSERT INTO posts (PostUUID,subid,date,pricing,post_status,UUID,Name,Phone,Email,Poscode,DateReg,Reputation,ReviewPlus,ReviewNeg,Sex,week_morning,week_afternoon,week_evening,weekend_morning,weekend_afternoon,weekend_evening,Status) VALUES(:PostUUID,:subid,now(),:pricing,:post_status,:UUID,:Name,:Phone,:Email,:Poscode,now(),:Reputation,:ReviewPlus,:ReviewNeg,:Sex,:week_morning,:week_afternoon,:week_evening,:weekend_morning,:weekend_afternoon,:weekend_evening,:Status)');
$stmt4->execute(array(
':PostUUID' => $post_unique_id,
':subid'=>$key,
':pricing'=>$value,
':post_status'=>1,
':UUID'=>$unique_id,
':Name'=>$name,
':Phone'=>$phone,
':Email' =>$email,
':Poscode'=>$postcode,
':Reputation'=>78,
':ReviewPlus'=>65,
':ReviewNeg'=>3,
':Sex'=>$gender,
':week_morning'=>$week_morning,
':week_afternoon'=>$week_afternoon,
':week_evening'=>$week_evening,
':weekend_morning'=>$weekend_morning,
':weekend_afternoon'=>$weekend_afternoon,
':weekend_evening'=>$weekend_evening,
':Status'=>0
));
# Affected Rows?
$stmt4->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
}
/*try
{
$sql = "SELECT *FROM authsessions WHERE useruuid =:uid";
$statement = $pdo->prepare($sql);
$statement->bindValue(':uid', $unique_id);
$statement->execute();
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array("id" => $row['useruuid']));}
header('Content-Type: application/json');
echo json_encode($json);
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}*/
// $unique_id=uniqid();
}
?>
You need to use json_encode because the AJAX call says dataType: "json".
echo json_encode($unique_id);
It worked when you echoed 123 because a decimal number is valid JSON. But uniqid returns a hex string, and this isn't valid JSON. You need to encode it with quotes around it.