I'm trying to convert PHP file to Prepared statements. The original file is as follows and it is 100% working before modification:
<?php
include 'connt.php';
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$Name = $obj['Name'];
$loginQuery = "select * from Users where Name = '$Name' ";
$check = mysqli_fetch_array(mysqli_query($con, $loginQuery));
if ($check) {
$check['result'] = 'Login Matched';
$SuccessMSG = json_encode($check);
echo $SuccessMSG;
} else {
$InvalidMSG = array("result" => "Invalid Username or Password Please Try Again");
$InvalidMSGJSon = json_encode($InvalidMSG);
echo $InvalidMSGJSon;
}
mysqli_close($con);
In the above code, I am checking the data if it matches or not by using the flutter language code:
Future CheckName() async {
setState(() {
visible = true;
});
// var url = 'https://///////////////.php';
var data = {'Name': nameController.text};
var response = await http.post(url, body: json.encode(data));
Map<String, dynamic> message = jsonDecode(response.body);
if (message['result'] == 'Login Matched') {
setState(() {
visible = false;
});
Navigator.push(context, MaterialPageRoute(builder: (context) => Main()));
} else {
setState(() {
visible = false;
});
_showMyDialog();
}
}
Now after modifying the php code as follows:
<?php
include 'connt.php';
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$Name = $obj['Name'];
$sql = "SELECT * FROM Users WHERE Name=?"; // SQL with parameters
$stmt = $con->prepare($sql);
$stmt->bind_param("s", $Name);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$user = $result->fetch_assoc(); // fetch data
if ($result) {
$check['result'] = 'Login Matched';
$SuccessMSG = json_encode($check);
echo $SuccessMSG;
} else {
$InvalidMSG = array("result" => "Invalid Username or Password Please Try Again");
$InvalidMSGJSon = json_encode($InvalidMSG);
echo $InvalidMSGJSon;
}
mysqli_close($con);
After modification as above on the code. Now it works, but even if the name is wrong, it works correctly, it does not check if the name is present or not.
How to convert the first file from PHP in a correct way to Prepared statements or can solve the existing error?
Related
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 am trying to make a ajax call to do a database update in my php class. However, it seems the class is being called but the parameters are not passed for some reason.
Here is my jquery:
$(".sendRSVP").click(function(e){
e.preventDefault();
var nameArray = [];
//var uniqueCode = parseInt($(this).find('.theCheckbox').attr('id'));
//var response = ($(this).find('.theCheckbox').is(":checked")) ? '1' : '0';
//the parameters passed should be uniqueCode and response which both gave legit values
if($("#displayContacts").is(":visible")){
$.get("submitRSVP.php", {rs: '1', resp: '12345'})
.done(function(rtn){
console.log(rtn); //error is returned
})
}
});
Here is my php code:
<?php
require 'dbh.php';
$rsvp = $REQUEST["rs"];
$response = $REQUEST["resp"];
session_start();
if(session_start()) $invitationCode = $_SESSION['login_user'];
$hint = "here1";
try{
$updateQuery = "UPDATE `db686470460`.`GuestWithPlusOnes` SET `Confirmed`= '$response' WHERE `GuestWithPlusOnes`.`UniqueID`= '$rsvp'";
$updateStmt = $conn->prepare($updateQuery);
$updateStmt->execute();
if ($updateStmt->rowCount() > 0) {
$hint = 'success';
}else {
$hint = 'error';
}
$_SESSION['login_user'] = $rsvp;
$updateStmt = null;
}
catch(Exception $e){
$hint = $e;
}
echo $hint;
?>
I definitely have a record in my table with that uniqueId because when I change the query to:
$updateQuery = "UPDATE `db686470460`.`GuestWithPlusOnes` SET `Confirmed`= '1' WHERE `GuestWithPlusOnes`.`UniqueID`= '12345'";
that updates as normal. Is there something else I could be missing?
I'm trying to get a number from a mysql line then outputting it to ajax. the number can't be a string because I will multiply it in ajax. This is what i have so far. I'm not sure what to do from here.
ajax:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var category = $("txtCat").val();
var number = $("txtNum").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
if ( user > 0 and user < 30 ){
alert(result);
}
else{
alert( 'invalid user ID');
}
});
});
});
php:
<?php
$userID = $_GET["ID"];
$amount = $_GET["amount"];
$category = $_GET["category"];
$num = $_GET["number"];
require "../code/connection.php";
$SQL = "select userAmount from user where userID= '$userID'";
$reply = $mysqli->query($SQL);
while($row = $reply->fetch_array() )
{
}
if($mysqli->affected_rows > 0){
$msg= "query successful";
}
else{
$msg= "error " . $mysqli->error;
}
$mysqli->close();
echo $msg;
?>
Pretty straightforward - you just grab the value from the row and cast it as a float.
while($row = $result->fetch_array() )
{
$msg = floatval($row['userAmount']);
}
if($msg > 0) {
echo $msg;
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
And one small change in your ajax call:
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
You need to add echo $row['userAmount']; inside or after your while loop, and drop the second echo. You should be able to take result within your AJAX code and use it as a number directly.
Here function(query), query is the response from the AJAX call. So your alert should be:
alert(query);
result is empty.
You also should be using prepared statements and outputting the value you want.
Something like:
<?php
$userID = $_GET["ID"];
$amount= $_GET["amount"];
require "../code/connect.php";
$SQL = "SELECT userAmount FROM user WHERE userID= ?";
$reply = $mysqli->prepare($SQL);
if($mysqli->execute(array($userID))) {
$row = $reply->fetch_array();
echo $row['amount'];
}
else
{
$msg = "error" . $mysqli->error;
}
$mysqli->close();
?>
Then JS:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
});
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt to convert the value to an integer/float in JS.
I have a jquery save script like :
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Your file is save as : '+ naam);
window.location.replace("index.php?id=latest");
}
else
{
alert('Not saved');
}
I save a div in save.php which creates an new id in the database
What I want to achive is were
window.location.replace("index.php?id=latest");
id=latest must become (id=id from last saved file).
I tried
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
window.location.replace("index.php?id="+MBId);
and
var MBID =
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo $MBId ?>
window.location.replace("index.php?id="+MBId);
They both failed.
How can I run the query in the if(naam !=null) statement?
At first place you must fix your jQuery POST... You don't use POST respond which is wrong.. You should wait for it and then continue with other actions
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam }, function(responde){
if(responde.id)
window.location.replace("http://yoururl.com/index.php?id="+responde.id);
else
alert("No responde...");
}, "json");
}
else
{
alert('Not saved');
}
For better results I suggest you to use JSON data in that post/respond..
At your PHP code you have to set:
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo json_encode(array('id'=>$MBId));
exit();
?>
P.S. For window.location.replace please set your FULL url: "http://localhost/index.php?id=" OR atleast put slash at start of it "/index.php?id="
Solution
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Uw moodboard is opgeslagen als '+ naam);
window.location.replace("index.php?id=<?php $q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = ($data[0] + 1); echo "$MBId";?>");
}
This Works for me , i didnt need to make a jquery var i could echo the variable in php.
And i had to add 1 cause the sql query is loaded when the page is loaded.
So the file isn't saved yet when i get the highest id.