Database not responding to form when input added - javascript

So my database does not add this data into the database when the button is pressed.
I have created a form, and all the id's are perfect and the email is a foreign key so it is taken from sessionStorage of the logged in user. I need help with why it is not working, I have no idea. The page alerts me "the order was successful" when I press submit but the data does not get stored in the database.
My SQL statement also works definitely, I tried it in my database.
Here are my php and js:
<?php
header("Content-Type: application/json; charset=UTF-8");
$servername = "localhost";
$username = "root";
$password = "leaf123";
$dbname = "laxmi";
// Create Connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed:" . mysqli_connect_error());
}
else
{
// Obtain the contents
$request = file_get_contents('php://input');
// decode json so PHP can use it
$jsonRequest = json_decode($request);
// Query
$sql = "INSERT INTO checkout(email, ccName, ccNumber, month, year, cvc) VALUES ('$jsonRequest->email', '$jsonRequest->ccName', '$jsonRequest->ccNumber', '$jsonRequest->month', '$jsonRequest->year', '$jsonRequest->cvc')"
}
// Execute Query
$results = mysqli_query($conn, $sql);
echo json_encode("success");
mysqli_close($conn);
my javascript
$(document).ready(function () {
//When the submit button on the checkout form is pressed.
$("#SubmitOrder").on("click", function () {
//store each individual entry into a separate variable.
var email = sessionStorage.getItem("loggedInUser");
var ccname = document.getElementById("ccName").value;
var ccnum = document.getElementById("ccNumber").value;
var month = document.getElementById("month").value;
var year = document.getElementById("year").value;
var cvc = document.getElementById("cvc").value;
//create an array with the details in.
var checkout = {
email: email,
ccname: ccname,
ccnum: ccnum,
month: month,
cvc: cvc,
}
//direct the user to the login page and alert them that their registration was successful.
alert("Your order was successful.")
window.location.href = "../index.html"
//posts the JSON object to the php file so it can fill the database, and converts the checkout array into JSON so it can be read.
var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout))
})
})

First off, you're displaying the success message before even trying to send the post request to your PHP file. So your first job is to re-order things
var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout));
alert("Your order was successful.");
window.location.href = "../index.html";
Secondly, you're currently not checking for a response from the server as to whether the request was successful or not. I've modified the example from the jQuery docs https://api.jquery.com/jquery.post/
var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout))
.done(function() {
alert("Your order was successful.");
window.location.href = "../index.html";
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
Once you're done with that, you'll want to look into returning a response from PHP to say whether the query worked etc, but the above is at least enough to get you something that works for now :)

Related

Upgrading my PHP chat system? (Making it only update new messages?)

JS:
"use strict";
$(document).ready(function () {
var chatInterval = 250; //refresh interval in ms
var $userName = $("#userName");
var $chatOutput = $("#chatOutput");
var $chatInput = $("#chatInput");
var $chatSend = $("#chatSend");
function sendMessage() {
var userNameString = $userName.val();
var chatInputString = $chatInput.val();
$.get("./write.php", {
username: userNameString,
text: chatInputString
});
$userName.val("");
retrieveMessages();
}
function retrieveMessages() {
$.get("./read.php", function (data) {
$chatOutput.html(data); //Paste content into chat output
});
}
$chatSend.click(function () {
sendMessage();
});
setInterval(function () {
retrieveMessages();
}, chatInterval);
});
Write.php:
<?php
require("connect.php");
//connect to db
$db = new mysqli($db_host,$db_user, $db_password, $db_name);
if ($db->connect_errno) {
//if the connection to the db failed
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
//get userinput from url
$username=substr($_GET["username"], 0, 32);
$text=substr($_GET["text"], 0, 128);
//escaping is extremely important to avoid injections!
$nameEscaped = htmlentities(mysqli_real_escape_string($db,$username)); //escape username and limit it to 32 chars
$textEscaped = htmlentities(mysqli_real_escape_string($db, $text)); //escape text and limit it to 128 chars
//create query
$query="INSERT INTO chat (username, text) VALUES ('$nameEscaped', '$textEscaped')";
//execute query
if ($db->real_query($query)) {
//If the query was successful
echo "Wrote message to db";
}else{
//If the query was NOT successful
echo "An error occured";
echo $db->errno;
}
$db->close();
?>
Read.php
<?php
require("connect.php");
//connect to db
$db = new mysqli($db_host,$db_user, $db_password, $db_name);
if ($db->connect_errno) {
//if the connection to the db failed
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
$query="SELECT * FROM chat ORDER BY id ASC";
//execute query
if ($db->real_query($query)) {
//If the query was successful
$res = $db->use_result();
while ($row = $res->fetch_assoc()) {
$username=$row["username"];
$text=$row["text"];
$time=date('G:i', strtotime($row["time"])); //outputs date as # #Hour#:#Minute#
echo "<p>$time | $username: $text</p>\n";
}
}else{
//If the query was NOT successful
echo "An error occured";
echo $db->errno;
}
$db->close();
?>
Basically everything works perfectly, except I want to allow people to copy and paste, but what the script is doing at the moment is updating every message at the chatinterval which is 250MS.
How can I make it so I can highlight a message and copy it?
So my question is, can I do this:
Can I make it only update the new messages that appear every 250-500MS instead of updating every last bit of HTML as that is a waste of resources (Especially if there was a lot of messages)
I hope you can help!
p.s. I don't want to use web sockets
To make it update just starting from the last message, get the ID of the last message, and then in your next $.get include the id of that message and get only messages that came after that.
And then use .append() in your javascript so you're not overwriting the whole thing.
It looks like you're already using jQuery. You can create a PHP script that only queries the database for entries newer than the newest one displayed, then use $.append to append the message to the <div> (or whatever other element) that holds it.
Also, as the commenter pointed out, you're still probably susceptible to SQL injection. Considering using PDO with prepared SQL statements.

My registration code is allowing the same email to register twice (only when the form is submitted multiple times in a row very fast) [duplicate]

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 6 years ago.
I have written some registration code with HTML, Javascript and php.
The registration process(at a higher level) is as follows:
The user:
1. Enters their email, name, and password(twice) to an HTML form.
2. They press "create account"
3. Their email is then searched for in my users table to see if it
exists.
4. If it exists then they are told they are already registered and provided with a link to the login screen.
5. If the email doesn't already exist then it is inserted (along with other user details) to the users table in my database
My code works well to achieve this, however on testing it I have found a fault. If the user presses "create account" multiple times very fast it allows the same email address to register twice. Is there anything I can do to stop this?
Here's my code:
JQuery/Javascript
$("#registration_form").on("submit", function(e){
//this is called when the form is submitted i.e when "create account" is pressed
e.preventDefault();
var registration_email = $('#registration_email').val();
var registration_password = $('#registration_password').val();
var registration_password_confirmation = $('#confirm_registration_password').val();
var registration_display_name = $('#registration_display_name').val();
//validate fields and check if passwords match.
//all values have passed validation testing therefore make ajax request
var params = { 'registration_email' : registration_email, 'registration_password' : registration_password , 'registration_display_name' : registration_display_name, 'app_root_url':app_root_url};
$.ajax({
url: app_root_url + 'login_registration/registration_processing.php',
data: JSON.stringify(params),
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
success: function(data){
var result = data;
var emailAlreadyExists = result.email_already_exists;
if(emailAlreadyExists){
//email already exists in our database and therefore the user is already registered so should use the login form
displayError('registration_feedback_message', 'This email already exists in the system. If you already have an account please login here!');
}else{
//email does not already exist in our database
}
}//end success
});//end ajax
});
registration_processing.php (the main part of this file)
include_once '../includes/app_functions.php';
$app_root_url = filter_var($json->app_root_url, FILTER_SANITIZE_URL);
$email = filter_var($json->registration_email, FILTER_SANITIZE_EMAIL);
$password = filter_var($json->registration_password, FILTER_SANITIZE_STRING);
$display_name = filter_var($json->registration_display_name, FILTER_SANITIZE_STRING);
//more data filtering is performed here
$userPrivilegeID = 1; //basic user privilege
$userHasPassword = 1; //boolean 1 or 0
$profileImage = "images/profile_images/blank-avatar.png";
$results = registerUser($password, $email, $isAvatarImage, $profileImage, $userPrivilegeID, $display_name, $userHasPassword, $pdoConnection);
//create an array to store all values that we want to send back to the client side.
$data = array();
if($results['exception_occurred'] == true){
$data['exception_occurred'] = true;
$data['exception_message'] = $results['exception_message'];
echo json_encode($data);
}else{
$data['exception_occurred'] = false;
if($results['email_already_exists'] == true){
//email already exists. user is already registered and therefore has a password
//need to show error to user to say they are already registered and should use the login form.
$data['email_already_exists'] = true;
echo json_encode($data);
}else{
//email didnt exist so they have been registered
$data['email_already_exists'] = false;
//create an array which we will encrypt as our JWT token
$token = array();
$token['userID'] = $results['user_id'];
$token['email'] = $email;
$data['userID'] = $results['user_id'];
$data['user_is_subscriber'] = true;
$data['valid_user'] = true;
$data['userDetails'] = getProfile($results['user_id'], $pdoConnection);
$data['usertoken'] = JWT::encode($token, 'secret_server_key');
//echo data back to ajax request on client side
echo json_encode($data);
}
}
registerUser function (in app_functions.php)
function registerUser($password, $email, $isAvatarImage, $profileImage, $userPrivilegeID, $display_name, $userHasPassword, $pdoConnection){
$data = array();
try{
$data['exception_occurred'] = false;
//first check if that email already exists just in case
$query = "SELECT COUNT(userID) FROM users WHERE emailAddress=:emailAddress";
$statement = $pdoConnection->prepare($query);
$statement->bindValue(':emailAddress', $email, PDO::PARAM_STR);
$statement->execute();
$rowCount = $statement->fetchColumn(0);
if($rowCount > 0){
//email already exists. user is already registered and therefore has a password
//need to show error to user to say they are already registered and should use the login form.
$data['email_already_exists'] = true;
return $data;
}else{
$data['email_already_exists'] = false;
$hashedPassword = password_hash($password, PASSWORD_DEFAULT, ['cost' => 12]);
$query = "INSERT INTO users (emailAddress, password, isAvatarImage, profileImage, userPrivilegeID, displayName, userHasPassword) VALUES (:emailAddress, :password, :isAvatarImage, :profileImage, :userPrivilegeID, :displayName, :userHasPassword)";
$statement = $pdoConnection->prepare($query);
$statement->bindValue(':emailAddress', $email, PDO::PARAM_STR);
$statement->bindValue(':password', $hashedPassword, PDO::PARAM_STR);
$statement->bindValue(':isAvatarImage', $isAvatarImage, PDO::PARAM_INT);
$statement->bindValue(':profileImage', $profileImage, PDO::PARAM_STR);
$statement->bindValue(':userPrivilegeID', $userPrivilegeID, PDO::PARAM_INT);
$statement->bindValue(':displayName', $display_name, PDO::PARAM_STR);
$statement->bindValue(':userHasPassword', $userHasPassword, PDO::PARAM_INT);
$statement->execute();
$data['user_id'] = $pdoConnection->lastInsertId();
return $data;
}
}catch(PDOException $e){
//throw new pdoDbException($e);
$data['exception_occurred'] = true;
$data['exception_message'] = $e->getMessage();
return $data;
}
}
One solution I can think of is to put a timer on the "create account" button so that multiple ajax requests can't be made so close together?
Edit
After reading some of your solutions I am looking into making the email field unique. thanks
I am working in phpMyAdmin so is it as simple as just pressing "unique"(highlighted in the image)?
Edit 2
I tried creating the email as a unique key and i get the following error:
Edit 3
To solve the error above (in Edit 2) I changed the collation of the email address field from utf8mb4_unicode_ci to utf8_unicode_ci and then I tried pressing "unique" again and it worked. Thank you all
You may add UNIQUE CONSTRAINT to your email field into the database. This way if you try to insert an email that already exists, it fails.
Make the email field in your database unique. I don't recommend PK because users may want to change their email address.
I always recommend doing validations on both the server and the client.
In this case, as everyone mentioned, in the server (Database) you should define a unique constraint on the e-mail field, so repeated e-mails will never actually happen.
I would also recommend to disable the "Create account" button after the first click on it. You could even change the name of the button to "... please wait" to indicate the operation is being executed. When you get the response from the server (either success or failure) you can enable it again. This will avoid any unnecessary successive calls to the server in the first place.
You have returned data in else case and not in if case now there are two options.
instead of returning data in else block return it outside the else block or
return data in if case too.
This causes when it founds the email id but does not return it will be as false if you check hence it allows to register the user to use same email id for two different accounts

mysql query from php isnt working but it works in a different php file

I'm trying to make a query from my MySQL database here is the code
<?php
$link = new MySQLi('localhost','root','Rrtynt','copy');
if(isset($_POST['id'])){
$name = $_POST['id'];
$profile = 'profile';
$thestring = $name.$profile;
//echo $thestring;
$result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$name'");
echo $result;
}
?>
the code for the query
$result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$name'");
works in a different php script the same exact code but it keeps giving me http 500 error, I'm using this to post from a javascript file
$.post("/getfirstfolder.php", { id: value1 }, function (data) {
cop = data;
console.log("Data: " + data);
});
if I take out
$result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$name'");
and just echo $thestring it works fine, I cant figure out the problem so thank you for your time and your help is greatly appreciated
The fact that you mentioned $thestring, makes me think that perhaps you should be using $thestring as the parameter to the query like this:
$result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$thestring'");

"CLI has stopped working" when trying to select all from an Oracle Database using JQuery?

I am attempting to use JavaScript and Jquery to search a database. I have set up a generic query.php file so that I can pass in the database and query and have it return an array. For some reason, when I try to select all using the *, my PHP server crashes with:
I am using the built in server with PHP 7.0.2. I am attempting to retrieve information from a Oracle database.
Here is the post statement:
$.post(DB1.filename,
{sid: DB1.sid,
username: DB1.username,
password: DB1.password,
host: DB1.host,
port: DB1.port,
sql: query},
function(res){
if(res == -1){
res = errorCode(DATABASE_CONNECTION_ERROR);
} else {
var a = parseObject(res);
var t = parseTable(a);
elements[TABLE].element.innerHTML = t;
}
log(FILE_NAME, "RETRIEVED query ");
}
);
Here is the query.php:
<?php
/* This script will connect to a database and search the given SQL string.
If the connection cannot be established, it will return -1. Otherwise, it will return a JSON array.
*/
//Parameters
$sql = $_POST["sql"];
//Database Information
$user = $_POST["username"];
$pass = $_POST["password"];
$host = $_POST["host"];
$port = $_POST["port"];
$sid = $_POST["sid"];
$connection = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = " . $host .")(PORT = " . $port . ")) (CONNECT_DATA = (SID = " . $sid . ")))";
//Establish connection
$conn = oci_connect($user, $pass, $connection);
//Check connection
if(!$conn){
echo -1;
} else {
//Query for the given SQL statement
$stRows = oci_parse($conn, $sql);
oci_execute($stRows);
oci_fetch_all($stRows, $res); //This is where the everything actually crashes
echo json_encode($res);
//Close the connection
oci_close($conn);
}
?>
So if I set the query as:
query = "select TABLE_NAME from ALL_TABLES";
everything works just fine. A table with a single column will be printed to the screen.
However, if I run:
query = "select * from ALL_TABLES";
I get the error above.
This happens regardless of which table I am attempting to connect to. My credentials are correct and I have tried different credentials as well. Any ideas why this is happening?
--UPDATE--
I tried hard coding the column names. I can select up to 8 columns before it crashes.There are 152 rows.
I circumvented the error by swapping the oci_fetch_all for oci_fetch_array as follows:
<?php
...
} else {
//Query for the given SQL statement
$stRows = oci_parse($conn, $sql);
oci_execute($stRows);
$res = array();
while($row = oci_fetch_array($stRows, OCI_NUM)){
$res[] = $row;
}
echo json_encode($res);
//Close the connection
oci_close($conn);
}
?>
This meant drastic changes to the function used to decode the JSON object array, but it does work. I will not mark this answer as correct though because I would very much like to know why my original code wasn't working...

Save data from dataTable to database

how can I save all my datatable data to my database?, im using jquery and php to do this dynamic.
$('#bot_guar').click( function () {
//var rows = $("#tabla1").dataTable().fnGetNodes();
var oTable = $('#tabla1').DataTable();
var data1 = oTable.rows().data();
//alert(data1.length);
$.ajax({
type:"POST",
dataType:'json',
url: "<?= Router::Url(['controller' => 'cab_facturas', 'action' => 'addDetFac'], TRUE); ?>/",//teacher//getdata/3
data:data1,
success: function(data){
alert(data);
}//success
});
});
this is what I had to POST the data from datatable, but I dunno why is the function to send to my php function that will insert.
You can consume the data object sent from your AJAX call as POST parameters or query string parameters depending on your settings. Consider you want to access firstname, lastname and email from your server side script. It can be done using:
$firstname = _POST['firstname'];
$lastname = _POST['lastname'];
$email = _POST['email'];
Now, Connect to your database and insert this data through your php script:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Its good practice to send a response to your call back functions so you can do this:
echo json_encode(array('status'=>"Success", message=""));
Your call back function will contain the data sent back from the php file. Since we are sending back a json string, we can make an object of it like this:
var myCallbackFunction = function(data){
var d = $.parseJSON(data)[0];
if(d.Status=="Success"){
//reload your datatable ajax
}else{
alert(d.message);
}
}
I hope that helped!

Categories

Resources