Random Queries Failing with MySql - php

I hope this question is not too broad but it is not with a specific piece of code. Basically at random times and on random queries I have failures in my code. Most of the time it seems like it is on my INSERT calls. UPDATE and DELETE still work fine, but INSERT will fail across the entire page for several hours at a time before mysteriously working again. The page is only being used and tested by myself currently.
One of the sample queries.
PHP
session_start();
$poster = $_SESSION['login_user'];
$conn = new PDO("mysql:host=localhost;dbname=spectrum",'root', '1234abcd');
$u = $_POST['user'];
$p = md5($_POST['pass']);
$e = $_POST['email'];
$fn = $_POST['first_name'];
$ln = $_POST['last_name'];
$t = $_POST['type'];
$sql = "INSERT INTO users(id, user, pass, email, type, first_name, last_name, poster) VALUES ('', :user, :pass, :email, :type, :first, :last, :poster)";
$q = $conn->prepare($sql);
$q->bindParam(":user", $u);
$q->bindParam(":email", $e);
$q->bindParam(":pass", $p);
$q->bindParam(":type", $t);
$q->bindParam(":first", $fn);
$q->bindParam(":last", $ln);
$q->bindParam(":poster", $poster);
$q->execute();
echo json_encode('User has been added.');
This is done through an Ajax call.
JQuery
var request;
if (request) {
request.abort();
}
var $form = f;
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: site + "/backend/formup.inc.php",
type: "post",
dataType: 'json',
data: serializedData
});
request.done(function (data){
if(data.location){
window.location.replace(data.location);
}
else{
alert(data);
location.reload(false);
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
alert(
"The following error occured: "+
textStatus, errorThrown
);
});
request.always(function (data) {
if(!data.tvar){
$inputs.prop("disabled", false);
}
});
Here is the HTML.
<form class="hidden" method="POST">
<input type="text" name="user" placeholder="Username" required/>
<input type="email" name="email" placeholder="Email" required/>
<input type="password" name="pass" placeholder="Password" required/>
<input type="text" name="first_name" placeholder="First Name" required/>
<input type="text" name="last_name" placeholder="Last Name" required/>
<input type="radio" name="type" value="0">Owner
<input type="radio" name="type" value="1">Employee
<input type="radio" name="type" value="2">Artist
<input type="radio" name="type" value="3">Venue
<input type="radio" name="type" value="4">Fan<br />
<input type="hidden" name="fname" value="add_user" />
<input type="submit" class="button" value="Add" />
</form>
Also I apologize if some formatting may be off with my questions. First time posting and getting used to the site.

Related

Getting SQL error while submitting form via ajax

I have a simple form with one input field and one submit button. When i click submit, i get error
This is the query in php. Query:
//Using MySQLi
$stmt = $con->prepare("INSERT INTO `emailsubscribe`
(email,medium,country)VAlUE(?,?,?)"); // Use prepared statements.
$stmt-> bind_param("sss", $email, $medium, $country);
$stmt-> execute();
This table has 3 columns email, medium and country.
$('#formoid').on('submit', function() {
$.ajax({
type: "POST",
url: "subscribe.php",
data: $(this).serialize(),
success: function(data){
$('.message').html(data).fadeIn();
}
});
return false;
});
<div class="message" style="color:black;"></div>
<form action="subscribe.php" title="" method="post" id="formoid">
<input type="email" id="email" name="email" minlength="7" size="40" placeholder="Enter your email here.." required><br><br>
<input type="hidden" name="medium" value="subbox" />
<input type="hidden" name="country" value="<?php echo $country; ?>" />
<input type="submit">
</form>
First, let's wrap up the HTML data.
<div class="message"></div>
<form action="subscribe.php" name="subscribeForm">
<input type="email" name="emailsub" minlength="7" size="40" placeholder="Enter your email here.."><br><br>
<select name="medium">
<option value="">Select Medium</option>
<option value="english">English</option>
<option value="hindi">Hindi</option>
<option value="japanese">Japanese</option>
</select>
<br><br>
<select name="country">
<option value="">Select Country</option>
<option value="India">India</option>
<option value="USA">USA</option>
<option value="Japan">Japan</option>
</select><br><br>
<input type="submit" id="action">
</form>
AJAX code below takes the form details and sends to subscribe.php. Note that document.subscribeForm below takes your form field variables and stores in the form. For this only name value in HTML part is enough. Hence, I have not added any id field in the HTML form fields.
$('#action').click(function() {
var form = document.subscribeForm;
var dataString = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr("action"),
data: dataString,
beforeSend: function(){
$('.message').hide();
$("#action").val('Please wait...');
},
success: function(data){
$('.message').html(data).fadeIn();
}
});
return false;
});
Once the data is sent to subscribe.php, it's now time to process it.
// Storing data in variables
$email = (!empty($_POST['emailsub'])?$_POST['emailsub']:null;
$medium = (!empty($_POST['medium'])?$_POST['medium']:null;
$country = (!empty($_POST['country'])?$_POST['country']:null;
if($_POST){
// Check if email submitted is empty or not. If yes, script will stop executing further.
if($email == null){
echo "Email is required";
exit();
}
// Check if medium submitted is empty or not. If yes, script will stop executing further.
if($medium == null){
echo "Medium is required";
exit();
}
// Check if country submitted is empty or not. If yes, script will stop executing further.
if($country == null){
echo "Country is required";
exit();
}
// All checks cleared. Process the data.
//Using MySQLi
$stmt = $con->prepare("INSERT INTO emailsubscribe(email, medium, country)VAlUES(?,?,?)"); // Use prepared statements.
$stmt-> bind_param($email, $medium, $country);
$stmt-> execute();
// Using PDO (Better: A big bonus is that you can use a readable `:name` instead of confusing `?`)
$stmt = $con->prepare("INSERT INTO emailsubscribe(email, medium, country)VAlUES(:email, :medium, :country)"); // Use prepared statements.
$stmt-> bindValue(':email', $email);
$stmt-> bindValue(':medium', $medium);
$stmt-> bindValue(':country', $country);
$stmt-> execute();
// Echo Message
if($stmt){
echo "Success";
}else{
echo "Error";
}
}
This is the proper way how you should process your forms.
Firstly I don't see any medium or country in your form as inputs. So I changed your HTML code
$('#formoid').on('submit', function() {
$.ajax({
type: "POST",
url: "subscribe.php",
data: $(this).serialize(),
success: function(response) {
$(this).hide(); //sets css display:none to form
var message = "Thank you!";
$('.container-fluid').html(message);
}
});
});
<form action="subscribe.php" title="" method="post" id="formoid">
<input type="email" id="emailsub" name="email" minlength="7" size="40" placeholder="Enter your email here.." required><br><br>
<input type="text" id="" name="medium" size="40" placeholder="Enter here.." required>
<input type="text" id="" name="country" size="40" placeholder="Enter here.." required>
<input type="submit">
</form>
Then in your subscribe.php do the following. Take note, I just copied your exact SQL code. Use prepared statements or PDO to avoid SQL injection
$qry = mysqli_query($con,"INSERT into `emailsubscribe` (email,medium,country) value ('".$_POST['email']."','".$_POST['medium']."','".$_POST['country']."')");

Undefined result from Ajax

I am passing some form variables through to a php page using Ajax, however when the php code runs the table rows are filled with the value undefined.
I have checked the php code, substituting the form variables and that works fine and so i am thinking that the problem is with the Ajax code,
AJAX
$(document).ready(function(){
$('form.submit').submit(function () {
var name = $(this).find('.name').attr('value');
var address = $(this).find('.address').attr('value');
var number = $(this).find('.number').attr('value');
var price = $(this).find('.price').attr('value');
var deposit = $(this).find('.deposit').attr('value');
var product = $(this).find('.product').attr('value');
var payment_type = $(this).find('.payment_type').attr('value');
var deal_date = $(this).find('.deal_date').attr('value');
var install_date = $(this).find('.install_date').attr('value');
var installed = $(this).find('.installed').attr('value');
var notes = $(this).find('.notes').attr('value');
var contract_received = $(this).find('.contract_received').attr('value');
// ...
$.ajax({
type: "POST",
url: "add.php",
data: "name="+ name +"& address="+ address +"& number="+ number +"& price="+ price +"& deposit="+ deposit +"& product="+ product +"& payment_type="+ payment_type +"& deal_date="+ deal_date +"& install_date="+ install_date +"& installed="+ installed +"& notes="+ notes +"& contract_received="+ contract_received,
success: function(){
$('form.submit').hide(function(){$('div.success').fadeOut();});
}
});
return false;
});
});
HTML
<form id="submit" name="submit" class="submit">
<input name="name" id="name" type="text" class="form-control" placeholder="Name"/><br />
<input name="address" id="address" type="text" class="form-control" placeholder="Address"/><br />
<input name="number" id="number" type="text" class="form-control" placeholder="Number"/><br />
<input name="price" id="price" type="text" class="form-control" placeholder="Price"/><br />
<input name="deposit" id="deposit" type="text" class="form-control" placeholder="Deposit"/><br />
<input name="product" id="product" type="text" class="form-control" placeholder="Product"/><br />
<input name="payment_type" id="payment_type" type="text" class="form-control" placeholder="Payment"/><br />
<input name="deal_date" id="deal_date" type="text" class="form-control" placeholder="Deal Date"/><br />
<input name="install_date" id="install_date" type="text" class="form-control" placeholder="Install Date"/><br />
<input name="installed" id="installed" type="text" class="form-control" placeholder="Installed"/><br />
<textarea name="notes" id="notes" cols="" rows="" class="form-control" placeholder="Notes"></textarea><br />
<input name="contract_received" id="contract_received" type="text" class="form-control" placeholder="Contract Received"/><br />
<input type="submit" name="button" id="button" value="Submit" />
</form>
PHP
$name = htmlspecialchars(trim($_POST['name']));
$address = htmlspecialchars(trim($_POST['address']));
$number = htmlspecialchars(trim($_POST['number']));
$price = htmlspecialchars(trim($_POST['price']));
$deposit = htmlspecialchars(trim($_POST['deposit']));
$product = htmlspecialchars(trim($_POST['product']));
$payment_type = htmlspecialchars(trim($_POST['payment_type']));
$deal_date = htmlspecialchars(trim($_POST['deal_date']));
$install_date = htmlspecialchars(trim($_POST['install_date']));
$installed = htmlspecialchars(trim($_POST['installed']));
$notes = htmlspecialchars(trim($_POST['notes']));
$contract_received = htmlspecialchars(trim($_POST['contract_received']));
$addClient = "INSERT INTO DATA (
name, address,number,price,deposit,product,payment_type,deal_date,install_date,installed,notes,contract_recieved)VALUES('$name','$address','$number','$price','$deposit','$product','$payment_type','$deal_date','$installed_date','$installed','$notes','$contract_received')";
mysql_query($addClient) or die(mysql_error());
You are making it very hard for yourself. There is no need to get all individual values from the form if you are sending the whole form. But if you do, you need to encode each value correctly using encodeURIComponent(). And don't send any spaces in your query string either.
The easiest solution is to have jQuery serialize your form and send that:
$.ajax({
type: "POST",
url: "add.php",
data: $('form.submit').serialize(), // or just: data: $(this).serialize(),
success: function(){
$('form.submit').hide(function(){$('div.success').fadeOut();});
}
});
Now all key-value pairs from the form will be sent correctly and jQuery will also take care of the encoding for you.
The correct syntax is http://api.jquery.com/jQuery.ajax/
data: {name: name, address: address, number: number}
and so on.

AJAX form not inserting values into SQL DB

I am trying to incorporate this code to allow me to register a user after their details are given. All details are to be inserted into the database, and then load the new page, all done using AJAX.
To help keep things in context. All pages are loaded within the #main-content div within index.php. They are all loaded via the same function used that you will see in the click.js portion upon ajax success. Register.php is simply one of the pages that loads within this div.
Currently, the form loads properly, and upon submission, the new page loads as per the ajax function. Nothing however is inserted into the database.
Disclaimer: I have not set this up yet to trim for security purposes. This is a matter of function first prior to setting up to protect against SQL injections.
register.php
<script src="js/click.js"></script>
<form action="click.js" method="post">
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name" /><br>
<label for="last_name" >Last Name:</label>
<input type="text" id="last_name" name="last_name" /><br>
<label for="username">Username:</label>
<input type="text" id="username" name="username" /><br>
<label for="password">Password:</label>
<input type="text" id="password" name="password" /><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" /><br>
<button type="submit" id="reg-submit" name="submit">Submit</button>
</form>
click.js
$(document).ready(function(){
$('#reg-submit').click(function() {
var firstName = $('#first_name').val();
var lastName = $('#last_name').val();
var userName = $('#username').val();
var password = $('#password').val();
var email = $('#email').val();
var dataString = 'name1=' + firstName + '&lastname1=' + lastName + '&user1=' + userName + '&password1=' + password + '&email1=' + email;
if (firstName == "" || lastName == "" || userName == "" || password == "" || email == "") {
alert('missing some information');
} else {
$.ajax({
type: "POST",
url: "usersubmit.php",
data: dataString,
cache: false,
success: function(){
$('#main-content').load('php/next-page.php').hide().fadeIn('slow');
}
});
};
return false;
});
});
the DB connection takes place within the users_db.php.
usersubmit.php
<?php
include 'users_db.php';
$first1=$_POST['name1'];
$last1=$_POST['lastname1'];
$username1=$_POST['user1'];
$pass1=$_POST['password1'];
$email01=$_POST['email1'];
$userinfo = $conn->prepare("INSERT INTO registered_users (FirstName, LastName, Username, Password, Email) VALUES ('$first1', '$last1', '$username1'', '$pass1', '$email01')");
$userinfo->execute();
$conn = null;
?>
Much appreciated!
If you see any other problems I may have here outside of the form simply not submitting, feel free to point them out.
The answer is that is not how you prepare statements :)
<?php
include 'users_db.php';
$first1=$_POST['name1'];
$last1=$_POST['lastname1'];
$username1=$_POST['user1'];
$pass1=$_POST['password1'];
$email01=$_POST['email1'];
$userinfo = $conn->prepare("INSERT INTO registered_users (FirstName, LastName, Username, Password, Email) VALUES (?, ?, ?, ?, ?)");
$userinfo->bind_param("sssss",$first1,$last1,$username1,$pass1,$email01);
$userinfo->execute();
// you shoud close the prep statement object
$userinfo->close();
//this is the way to kill the conn
$conn->close();
?>
This is assuming your connection to database works :)

Input fields are empty after .submit jquery statement

I'm trying to send data using an ajax call inside of a ('#form').submit call but all the inputs of the forms are empty when I didn't intend them to be. I thought it may of had something to do with the $(document).ready statement being in the incorrect location for things to work properly but I couldn't get it to work.
<script>
(function($){
$(document).ready( function() {
$("#success").hide();
$("#inval_email").hide();
$("#text_selection").on("change", function() {
var id = $("#text_selection option:selected").attr("value");
$("#inv_text").html($("#"+id).html());
});
$("#invitation_form").submit(function(e){
var email = $('#email').val();
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var message_title = $('#message_title').val();
var article_title = $('#article_title').val();
var reference_location = $('#reference').val();
var inv_text = $('#inv_text').html();
var request;
alert(first_name);
e.preventDefault();
request = $.ajax({
type: 'POST',
url: BASE_URL+"wp-content/themes/Flatter/ajax/send_invite.php",
dataType: "text",
data: { first_name: first_name, last_name: last_name, email: email, message_title: message_title, article_title: article_title, reference_location: reference_location, inv_text: inv_text },
success: function(data){
console.log(data)
if(data=="true"){
$("#invitation").hide();
$("#success").show();
}
if(data=="false"){
$("#inval_email").show();
}
}
});
});
});
})(jQuery);
</script>
<div class="col-md-4">
<div id="success" hidden><br><br>Invitation sent successfully!</div>
<div id="invitation">
<br><br><br></br><h1>Invitation Form</h1>
<form id = "invitation_form">
First Name:<input id="first_name" type="text" name="first_name" required>
Last Name:<input id="last_name" type="text" name="last_name" required>
Email Address:<input id="email" type="text" name="email" required>
Message Title:<input id="message_title" type="text" name="message_title" required>
Article Title:<input id="article_title" type="text" name="article_title" required>
Reference Location:<input id="reference" type="text" name="reference" required>
Message:<textarea id="inv_text" style="resize: none" rows="10" placeholder="Select invitation type..." readonly required></textarea>
Invitation Type:
<select id="text_selection">
<option value="empty_field"></option>
<option value="community_inv_text">Community Invitation</option>
<option value="content_submission_inv" >Content Submission Invitation</option>
<option value="individual_inv">Individual Invitation</option>
<option value="content_submission_and_individual_inv">Content Submission and Individual Invitation</option>
<option value="contributor_content_submission_inv">Contributor Content Submission Invitation</option>
</select>
<input id="submit_inv" type="submit" value="Invite">
</form>
I would greatly appreciate some help in this matter. The point of this code is to collect information from the user and send the data to another file so it can be processed. Thanks for any help in advance.
I figured it out. There was a CSS file that was modifying elements under the same name as the ones I am using in my file (i.e. first_name, last_name, email, etc.).

jQuery Mobile Ajax Form Submission / Insert Data into MySQL DB

I am having a problem with the $_POST array that comes from my form.
Here is the code for my form:
<form id="form-add-client" method="post" data-ajax="false">
<input type="text" name="companyName" id="companyName" value="" placeholder="Company Name" />
<input type="text" name="email" id="email" value="" placeholder="Email" />
<br />
<input type="text" name="firstName" id="firstName" value="" placeholder="First Name" />
<input type="text" name="lastName" id="lastName" value="" placeholder="Last Name" />
<input type="tel" name="workPhone" id="workPhone" value="" placeholder="Work Phone" />
<input type="tel" name="mobilePhone" id="mobilePhone" value="" placeholder="Mobile Phone" />
<br />
<input type="text" name="streetAddress" id="streetAddress" value="" placeholder="Street Address" />
<input type="text" name="city" id="city" value="" placeholder="City" />
<input type="text" name="postalCode" id="postalCode" value="" placeholder="Postal Code" />
<br />
<input type="button" data-theme="b" name="submit" id="submit-add-client" value="Add Client" />
</form>
Here is the jQuery ajax code:
// Add Client
$(document).on('pagebeforeshow', '#add-client', function(){
$(document).on('click', '#submit-add-client', function() { // catch the form's submit event
if($('#companyName').val().length > 0 && $('#email').val().length > 0){
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
// fetch the data for the form
var data = $('#form-add-client').serialize();
$.ajax({url: 'http://www.website.co.nz/goflowdata/addclient.php',
data: data,
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.loading('show'); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.loading('hide'); // This will hide ajax spinner
},
success: function (result) {
if(result.status) {
$.mobile.changePage("#add-client-success");
} else {
alert('Add client unsuccessful!');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
});
Here is the code from the addclient.php file:
<?php
header("Access-Control-Allow-Origin: *");
require_once("debug/chromephp.php");
$formData = $_POST;
ChromePhp::log($_POST);
require_once("config.php");
$companyName = $formData['companyName'];
$email = $formData['email'];
$firstName = $formData['firstName'];
$lastName = $formData['lastName'];
$workPhone = $formData['workPhone'];
$mobilePhone = $formData['mobilePhone'];
$streetAddress = $formData['streetAddress'];
$city = $formData['city'];
$postalCode = $formData['postalCode'];
$sql="INSERT INTO clients (companyName, email, firstName, lastName, workPhone, mobilePhone, streetAddress, city, postalCode) VALUES ('$companyName', '$email', '$firstName', '$lastName', '$workPhone', '$mobilePhone', '$streetAddress', '$city', '$postalCode')";
$result = mysql_query($sql);
if($result) {
// Success
$output = array('status' => true, 'massage' => 'Success!');
echo json_encode($output);
} else {
// Failed
$output = array('status' => false, 'massage' => 'Failed!');
echo json_encode($output);
}
?>
My problem is with the $formData['postalCode']; variable. It seems to be emtpy. I have used ChromePHP to try debug the issue and it returns the form data before being posted via ajax. In the serialized string the postalCode is there as you can see the console screenshot below. Can anyone see why this is happening? Any help is much appreciated.
When I use ChromePHP to log the contents of $_POST to the console I get this twice:
Object {companyName: "TestCompany", email: "test#email.com", firstName: "John", lastName: "Doe", workPhone: "01234567"…} city: "Testcity" companyName: "TestCompany" email: "test#email.com" firstName: "John" lastName: "Doe" mobilePhone: "012345678" postalCode: "" streetAddress: "7 Test Street" workPhone: "01234567" proto: Object
Screenshot:
Screenshot of MySQL table row:
Screenshot of console logged variables:

Categories