Values not inserting in database with php - php

I have created a user register form with php jquery and sql and i am
trying to enter the details in database via ajax request, code is
executing perfectly but values are not entering in the database, and i
have checked my query too by running it in the sql editor query also
working fine,
can you tell where is the error ?
<!DOCTYPE html>
<html>
<head>
<title>Login Register Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
/**
* Created by pratyush on 8/28/14.
*/
$(function(){
$("input[name='btn_submit_reg']").click(function(){
registerUser();
});
$("input[name='btn_submit_login']").click(function(){
loginUser();
});
});
function registerUser(){
if(IsValidFormReg()){
var frm = $(".register").serialize();
$.ajax({
url : 'modal/registerdao.php',
type : 'POST',
data : frm,
success : function(result) {
if (result.indexOf("correct") > -1) {
alert(frm);
window.location.replace("registrationconfirm.php");
}
}
});
}
}
function IsValidFormReg()
{
var valid= true;
var username = $("input[name='username_reg']").val();
var userpass = $("input[name='userpass_reg']").val();
var email = $("input[name='useremail_reg']").val();
if(username.length==0){
valid = false;
$("input[name='username_reg']").addClass("formerror");
}
if(userpass.length==0){
valid = false;
$("input[name='userpass_reg']").addClass("formerror");
}
if(email.length==0){
valid = false;
$("input[name='useremail_reg']").addClass("formerror");
}
else{
if(checkemail(email)==false){
valid = false;
$("input[name='useremail_reg']").addClass("formerror");
alert("please enter valid email");
}
}
if(!valid)
$(".formentrieserror").html(" Please fill correct form entries...");
else
$(".formentrieserror").html(" ");
return valid;
}
function checkemail(email){
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(email.length>0){
if (!filter.test(email))
return false;
else
return true;
}
else
return false;
}
function loginUser(){}
<style>
.formerror{border: solid 2px red;}
</style>
</head>
<body>
<h2>Login Form</h2> <br><br>
<form class="login">
<input type="text" name="username_login" placeholder="user name"> <br> <br>
<input type="password" name="userpass_login" placeholder="password"><br> <br>
<input type="button" name="btn_submit_login" value="Login">
</form>
<br><br>
<h2>Registration Form</h2>
<br><br>
<form class="register">
<input type="text" name="username_reg" placeholder="user name"> <br> <br>
<input type="password" name="userpass_reg" placeholder="password"><br> <br>
<input type="email" name="useremail_reg" placeholder="email"><br> <br>
<input type="button" name="btn_submit_reg" value="Register">
</form>
<div class="formentrieserror"></div>
</body>
</html>
//registerDao.php..................................//
<?php
class RegisterUserInfo{
public $userName;
public $userPassword;
public $userEmail;
}
class userRegisterDao {
function RegisterUser($registration_info) {
include_once ("database.php");
$qry = "insert into userdetails(
userName,
userPassword,
userEmail)
values('".$registration_info->userName."','"
.$registration_info->userPassword."','"
.$registration_info->userEmail."')";
return Database::executeQuery($qry); // return true or false
}
}
$userName = mysql_escape_string($_REQUEST ['userName']);
$userPassword = mysql_escape_string($_REQUEST ['userPassword'] );
$userEmail = mysql_escape_string($_REQUEST ['userEmail'] );
$registration_info = new RegisterUserInfo();
$registration_info->userName=$userName;
$registration_info->userPassword=$userPassword;
$registration_info->userEmail=$userEmail;
$dao = new userRegisterDao();
$insert = $dao->RegisterUser($registration_info);
if($insert===true){
echo "correct";
}
else
echo "invalid";
?>

Change this line
$userName = mysql_escape_string($_REQUEST ['userName']);
$userPassword = mysql_escape_string($_REQUEST ['userPassword'] );
$userEmail = mysql_escape_string($_REQUEST ['userEmail'] );
to this
$userName = mysql_escape_string($_REQUEST ['username_reg']);
/* changed ^^ */
$userPassword = mysql_escape_string($_REQUEST ['userpass_reg'] );
/* changed ^^ */
$userEmail = mysql_escape_string($_REQUEST ['useremail_reg'] );
/* changed ^^ */

I see this alot... Ajax with no error handler, just success handlers. Why not have php return errors to ajax and output to console IE console.log( some_error ) . It will make debugging a lot easier in the future.
I also see that there is no sql exception handling. That would have shown you that no column exists by that name during attempted insertions.
just a few debugging tips going forward, good luck.

Related

How to redirect React submit button to php page

I have created a form with live validation in react, but I want to post this form to a PHP page so it gets inserted into the database. The code currently validates but doesn't allow me to access the PHP page, I have access to the SQL database which is on config page and it works well.
react js form
<!DOCTYPE html>
<?php
include ("includes/header.php");
?>
<html lang="en">
<title>Demostration of Forms in React</title>
<script src= "https://unpkg.com/react#16/umd/react.production.min.js"></script>
<script src= "https://unpkg.com/react-dom#16/umd/react-dom.production.min.js"></script>
<script src= "https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
<body>
<h1> Register Page</h1>
<div id="root"></div>
<script type="text/babel">
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
//this.state = {value: 'Write your Name'};
this.handleChange = this.handleChange.bind(this);
this.password = this.password.bind(this);
this.manager = this.manager.bind(this);
this.phoneChange = this.phoneChange.bind(this);
this.emailChange = this.emailChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
//this.setState({value: event.target.value.toLowerCase()});
//perform validation length of the input values or others
//const textval = this.state.value;
var textval = this.state.value;
//if ((textval.length < 5) || (textval.length > 15))
//alert("Your Character must be 5 to 15 Character");
//user validation of the special characters
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < textval.length; i++) {
if (iChars.indexOf(textval.charAt(i)) != -1) {
alert ("Your username should not have !##$%^&*()+=-[]\\\';,./{}|\":<>? \nThese are not allowed.\n Please remove them and try again.");
//return false;
}
}
//if(isNaN(textval))
//alert(textval);
}
phoneChange(event){
this.setState({phone: event.target.value});
var textval2 = this.state.phone;
var iChars2 = "0123456789";
for(var j = 0; j< textval2.length; j++){
if(iChars2.indexOf(textval2.charAt(j)) == -1){
alert("Your phone number should be between 0 and 9");
}
}
}
password(event){
this.setState({password: event.target.value});
}
manager(event){
this.setState({manager: event.target.value});
}
emailChange(event){
this.setState({email: event.target.value});
var emailval = this.state.email;
var emailCheck= "#.";
for(var i =0; j<emailval.length; i++){
if(emailval.indexOf('#')>-1){
alert("Your email must contain an #");
}
}
}
//without .preventDefault() the submitted form would be refreshed
handleSubmit(event) {
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" id="reg_name" value={this.state.value} onChange={this.handleChange} /><br/><br/>
Email:
<input type="text" id="reg_email" value={this.state.email} onChange={this.emailChange} /><br/><br/>
Phone:
<input type="text" id="reg_phone" value={this.state.phone} onChange={this.phoneChange} /><br/><br/>
Password:
<input type="password" name="reg_password" value={this.state.password} onChange={this.password} /><br/><br/>
Is this an manager account:<br/>
<input type="checkbox" name="reg_manager" value={this.state.manager} onChange={this.manager}/> <br/><br/>
</label>
<br/>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
</script>
</body>
</html>
PHP page to insert database.
<!DOCTYPE html>
<?php
include ("includes/header.php");
$firstname = $_POST['reg_fname'];
//$lastname = $_POST['reg_lname'];
$email = $_POST['reg_email'];
$phone = $_POST['reg_phone'];
$password = $_POST['reg_password'];
//$password2 = $_POST['reg_password2'];
$manager = $_POST['reg_manager'];
if ($manager='on') {
$dbadmin = 1;
}else{
$dbadmin = 0;
}
$query = "INSERT INTO users(firstname,,email,password,manager) VALUES(?,?,?,?,?)";
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
//prepare and bind
if ($stmt = $dbo->prepare($query)) {
$stmt->bind_param("sssss", $firstname,$email,$hashed_password,$dbadmin);
$stmt->execute();
$stmt->close();
}
?>
<html>
<head>
<title>Registered user</title>
</head>
<body>
<h2>Registered User<?php echo ($firstname) ; ?></h2>
</body>
</html>
you can use axios in react ensuite
after you use his post and get functions ...
via the link of your API or backend
here is an example
  axios.post (http://localhost: 8800/ data /, {username: username}). then (res => {
     console.log (rec); // for example print : i get username from backen
   });

how can i return values from server request to the main page and use them as variables

login.php
<?php
//get post data
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
$nume = $_POST['nume'];
$class = $_POST['class'];
// Here I connect to the database and search for $user
// if $user is found, i want to:
alert("succes"); // optional, just a reasurance
$name =; // the name of the $user in database
$class =; // the class of the $user in database
// here i want to return the information that i need for main page
echo $name;
echo $class;
?>
a.html
<html>
<head>
<script type="text/javascript">
function checkForm(){
var name = document.forms[0].user.value;
if (name.length < 3) {
alert("Username is too short");
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<form action="login.php" method="POST" onsubmit="return checkForm()">
User: <input type="text" name="user"/>
Password: <input type="password" name="pass"/>
<input type="hidden" name="nume"/>
<input type="hidden" name="class"/>
<input type="submit"/>
</form>
</body>
</html>
How do I store the return values from login.php in two variables that i need to further change my main page?
For example how can I have in the main page X = $nume and y = $class with values from login.php?

Form validation to see if the email already excists in the MySQL database

At the moment I have a form (PHP & jQuery) with validations. I want to add a validation to check if the email address of a new user is already in the MySQL database or not.
At the moment there are 3 (IF) validations already for the name and email in jQuery:
function validate() {
var output = true;
$(".signup-error").html('');
if($("#personal-field").css('display') != 'none') {
if(!($("#name").val())) {
output = false;
$("#name-error").html("Name required!");
}
if(!($("#email").val())) {
output = false;
$("#email-error").html("Email required!");
}
if(!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#email-error").html("Invalid Email!");
output = false;
}
I would like to have a 4th one to check if the email address is already in the MySQL database.
The complete PHP file with jQuery:
<?php
include 'db_connection.php';
if(isset($_POST['finish'])){
$name = '"'.$dbConnection->real_escape_string($_POST['name']).'"';
$email = '"'.$dbConnection->real_escape_string($_POST['email']).'"';
$password = '"'.password_hash($dbConnection->real_escape_string($_POST['password']), PASSWORD_DEFAULT).'"';
$gender = '"'.$dbConnection->real_escape_string($_POST['gender']).'"';
$sqlInsertUser = $dbConnection->query("INSERT INTO users (name, password, email, gender) VALUES($name, $password, $email, $gender)");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/text.css" />
<link rel="stylesheet" href="css/960.css" />
<link rel="stylesheet" href="css/demo.css" />
<script src="scripts/jquery-1.10.2.js"></script>
<style>
CSS CODE
</style>
<script>
function validate() {
var output = true;
$(".signup-error").html('');
if($("#personal-field").css('display') != 'none') {
if(!($("#name").val())) {
output = false;
$("#name-error").html("Name required!");
}
if(!($("#email").val())) {
output = false;
$("#email-error").html("Email required!");
}
if(!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#email-error").html("Invalid Email!");
output = false;
}
}
if($("#password-field").css('display') != 'none') {
if(!($("#user-password").val())) {
output = false;
$("#password-error").html("Password required!");
}
if(!($("#confirm-password").val())) {
output = false;
$("#confirm-password-error").html("Confirm password required!");
}
if($("#user-password").val() != $("#confirm-password").val()) {
output = false;
$("#confirm-password-error").html("Password not matched!");
}
}
return output;
}
$(document).ready(function() {
$("#next").click(function(){
var output = validate();
if(output) {
var current = $(".active");
var next = $(".active").next("li");
if(next.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+next.attr("id")+"-field").show();
$("#back").show();
$("#finish").hide();
$(".active").removeClass("active");
next.addClass("active");
if($(".active").attr("id") == $("li").last().attr("id")) {
$("#next").hide();
$("#finish").show();
}
}
}
});
$("#back").click(function(){
var current = $(".active");
var prev = $(".active").prev("li");
if(prev.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+prev.attr("id")+"-field").show();
$("#next").show();
$("#finish").hide();
$(".active").removeClass("active");
prev.addClass("active");
if($(".active").attr("id") == $("li").first().attr("id")) {
$("#back").hide();
}
}
});
});
</script>
</head>
<body>
<div class="container_12">
<div class="grid_8">
<p>
TEXT<br>TEXT<br>TEXT<br>TEXT<br>TEXT
</p>
</div>
<div class="grid_4">
<p>Register new FC Magnate</p>
<div class="message"><?php if(isset($message)) echo $message; ?></div>
<ul id="signup-step">
<li id="personal" class="active">Personal Detail</li>
<li id="password">Password</li>
<li id="general">General</li>
</ul>
<form name="frmRegistration" id="signup-form" method="post">
<div id="personal-field">
<label>Name</label><span id="name-error" class="signup-error"></span>
<div><input type="text" name="name" id="name" class="demoInputBox"/></div>
<label>Email</label><span id="email-error" class="signup-error"></span>
<div><input type="text" name="email" id="email" class="demoInputBox" /></div>
</div>
<div id="password-field" style="display:none;">
<label>Enter Password</label><span id="password-error" class="signup-error"></span>
<div><input type="password" name="password" id="user-password" class="demoInputBox" /></div>
<label>Re-enter Password</label><span id="confirm-password-error" class="signup-error"></span>
<div><input type="password" name="confirm-password" id="confirm-password" class="demoInputBox" /></div>
</div>
<div id="general-field" style="display:none;">
<label>Gender</label>
<div>
<select name="gender" id="gender" class="demoInputBox">
<option value="female">Female</option>
<option value="male">Male</option>
</select></div>
</div>
<div>
<input class="btnAction" type="button" name="back" id="back" value="Back" style="display:none;">
<input class="btnAction" type="button" name="next" id="next" value="Next" >
<input class="btnAction" type="submit" name="finish" id="finish" value="Finish" style="display:none;">
</div>
</form>
</div>
The "db_connection.php" file:
<?php
define('_HOST_NAME', 'localhost');
define('_DATABASE_USER_NAME', 'root');
define('_DATABASE_PASSWORD', '****');
define('_DATABASE_NAME', '****');
$dbConnection = new mysqli(_HOST_NAME, _DATABASE_USER_NAME, _DATABASE_PASSWORD, _DATABASE_NAME);
if ($dbConnection->connect_error) {
trigger_error('Connection Failed: ' . $dbConnection->connect_error, E_USER_ERROR);
}
?>
I tried to create this validation from other examples that were given here on the website. But, no success. Please, it would be great if somebody could help me a little further.
UPDATE: With the help of Suyog I changed the files. But, it doesn't seem to work yet. Here are the files that I use at the moment: fcmagnate.com/files.zip
The form works till the moment the validation of the email address in the database starts, than it stops.
You will have to make use of JQuery AJAX for this.
Write a function in AJAX to send email to php gage where we will check the existance of email.
<script>
function checkEmail(eMail)
{
$.ajax({
url: 'check_email.php',
data: {emailId: eMail},
type: 'post',
success: function (data) {
if(data == '1')
return false;
else
return true;
}
});
}
</script>
Then you can call this function
<script>
function validate()
{
var output = true;
$(".signup-error").html('');
if($("#personal-field").css('display') != 'none')
{
if(!($("#name").val()))
{
output = false;
$("#name-error").html("Name required!");
}
if(!($("#email").val()))
{
output = false;
$("#email-error").html("Email required!");
}
if(!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/))
{
$("#email-error").html("Invalid Email!");
output = false;
}
if(!checkEmail($("#email").val()))
{
$("#email-error").html("Email already exist!");
output = false;
}
}
}
</script>
Youe check_email.php file will contain the code as follows
<?php
include 'db_connection.php';
if(isset($_POST['emailId']))
{
$email = '"'.$dbConnection->real_escape_string($_POST['emailId']).'"';
$sqlCheckEmail = $dbConnection->query("SELECT user_id FROM users WHERE LOWER(email) like LOWER('%".$email."%')");
if($sqlCheckEmail->num_rows == 1)
echo '1';
else
echo '0';
}
?>
Use Ajax jQuery.ajax on client side to communicate with server side reusing your php code mentioned.

keeping first field in html form after submitting then have a master submit button after someone is done with the first field

I am currently using this php form to submit into our mySQL database with a "chip_number" and "order_number" also with a date and time stamp. We want to use this with no keyboard or mouse, just a scanner. Currently it tabs the first field and when the second field is scanned the form is submitted, which is working as intended but it completely starts the form over, i would like it to keep the first field (order_number) after submitting so we can scan multiple "chip_numbers" on the same "order_number" then have a Master submit button if you will to send it all through when the employee is done with that order number and start with a blank form. This is the script i am using. thanks to all in advance!
<!-- Insert -->
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MICROCHIP_TBL (chip_number,order_number)
VALUES
('$_POST[chip_number]','$_POST[order_number]')";
IF (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: TRY AGAIN HUMAN!";
}
mysqli_close($conn);
?>
<html>
<head>
<!-- Validate form function -->
<!--<script type="text/javascript">
// function validateForm()
// {
// var x=document.forms["chip_insert"]["order_number"].value;
// var y=document.forms["chip_insert"]["chip_number"].value;
// if (x==null || x=="")
// {
// alert("Please enter an Order Number.");
// document.forms["chip_insert"]["order_number"].focus();
// return false;
// }
// if (y==null || y=="")
// {
// alert("Please enter a Microchip Number.");
// document.forms["chip_insert"]["chip_number"].focus();
// return false;
// }
// }
</script>
-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function getNextElement(field) {
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
return form.elements[++e % form.elements.length];
}
function tabOnEnter(field, evt) {
if (evt.keyCode === 13) {
if (evt.preventDefault) {
evt.preventDefault();
} else if (evt.stopPropagation) {
evt.stopPropagation();
} else {
evt.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
</script>
</head>
<body onLoad="document.chip_insert.order_number.focus();">
<center>
<h1>Jeffers HomeAgain Microchip Entry</h1>
<form name="chip_insert" id="chip_insert" action="<?php echo $PHP_SELF;?>" onsubmit="return validateForm()" method="post">
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
Tag Number: <input tabindex="2" maxlength="15" type="text" name="chip_number" id="chip_number" required="required" /><br /><br />
<input tabindex="7" type="submit" />
</center>
</form>
header('Location: http://JVSIntranet/microchip/homeagain.php');
This code redirects back to the form, I guess. You should add the ordernumber so it can be picked up by the form.
$ordernr = $_POST['order_number'];
header("Location: http://JVSIntranet/microchip/homeagain.php?order_number=$ordernr"); //mark the double quotes
in your form code you will have to use something like
<?php $value = (isset($_GET['order_number'])) ? " value=$_GET['order_number'] " : ""; ?>
Order Number: <input tabindex="1" maxlength="11" type="text" name="order_number" id="order_number" <?php echo $value; ?> required="required"onkeydown="return tabOnEnter(this,event)" /><br /><br />
I finally got it. i had to take out the Return function from my form and i added this to my script:
$value = "";
if( isset( $_POST ["order_number"] )) $value = $_POST ["order_number"];
then i put this in my input line and it works fine:
value="<?php echo $value; ?>"

don't submit form if form is empty

this is my first post and i'm rather new to php + ajax.
I have most of my coding set up only problem now is that when i press the submit button an notification shows up that only should show up when the text fields aren't empty.
This is my code:
<head><script>
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
alert("Thank you for subscribing to SHCA");
document.forms["ContactForm"].reset();
});
});
</script> </head>
followed by some php coding:
<?php
if(strlen($_POST['name']) > 0 AND strlen($_POST['email']) > 0)
{
if(isset($_POST['submit']))
{
$hostdb = '';
$namedb = '';
$userdb = '';
$passdb = '';
$conn = mysqli_connect($hostdb , $userdb, $passdb ,$namedb);
$sql = "INSERT INTO subscribers (name, email) VALUES('$_POST[name]', '$_POST[email]')";
if (!mysqli_query($conn, $sql))
{
die('Error: ' .mysql_error($conn));
}
if (!mysqli_ping($conn)) {
echo 'Lost connection, exiting after query #1';
exit;
}
mysqli_close($conn);
}}
else
{
?>
<form id="ContactForm" action="" method="post">
<label for="author">Name:</label> <input type="text" id="name" name="name" class="required input_field float_r" />
</br>
</br>
<label for="email">Email:</label> <input type="text" id="email" name="email" class="validate-email required input_field float_r" />
<div class="cleaner h10"></div>
<input type="submit" value="Subscribe" id="submit" name="submit" class="submit_btn float_l" />
</form>
<?php } ?>
hope anyone here is able to tell me what i should do to only show the "Thank you for subscribing to SHCA" message when the textfields aren't empty
final anwser Dereck forgot the '' in the objects so shout out to dereck for helping me!
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
if( !$('#name').val()) {
alert("please enter your name");
}
if(!$('#email').val()) {
alert("plese enter your email adress");
}
else{
alert("Thank you for subscribing to SHCA");
}
document.forms["ContactForm"].reset();
});
});
You need to check the contents of the fields before submitting to the server, a simple script method can check before you submit. If the fields are empty then display an error messge and don't submit the form.
function SubmitDetails()
{
if(window.ContactForm.name.value == "")
{
window.alert("Please enter a name");
return;
}if(window.ContactForm.email.value == "")
{
window.alert("Please enter an email" );
return;
}
window.ContactForm.submit();
}
This should do it without having to do a refresh
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
if( !$(#name).val() || !$(#email).val()) {
//don't display
}else{
alert("Thank you for subscribing to SHCA");
}
document.forms["ContactForm"].reset();
});
});

Categories