well I am trying to insert user data and I made these codes , the record is being created but there is no data in it , just to clarify I have include the files and I am connected to the database and I think I declared all the necessary objects , if you know what is wrong I would appreciate a bit more explaining I am a beginner
addUser.php
<div id="message" class="flex-row align-center flex-nowrap">
<h4 class="heading flex-1"></h4>
</div>
<div class="flex-row form-row">
<div class="flex-column create-session-sidebar__column">
<form class="form" method="post">
<div class="Faseeh-form-input outlined"><label class="label">الاسم الاول</label>
<input id="fname" placeholder="" type="text" value=""></div>
<div class="Faseeh-form-input outlined"><label class="label">الاسم الثاني</label>
<input id="lname" placeholder="" type="text" value=""></div>
<div class="Faseeh-form-input outlined"><label class="label">اسم المستخدم</label>
<input id="username" placeholder="" type="text" value=""></div>
<div class="Faseeh-form-input outlined"><label class="label">البريد الالكتروني</label>
<input id="email" placeholder="" type="email" value=""></div>
<div class="Faseeh-form-input outlined"><label class="label"> الالكتروني</label>
<input id="password" placeholder="" type="password" value=""></div>
<div class="flex-row form-row">
<button id="addUser" class="Faseeh-btn Faseeh-btn Faseeh-btn-primary" type="submit">تسجيل</button>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function() {
NewUser();
});
function NewUser() {
$(document).on('click', '#addUser', function() {
var fname = $('#fname').val();
var lname = $('#lname').val();
var username = $('#username').val();
var email = $('#email').val();
var password = $('#password').val();
var data = "fname=" + fname + "&lname=" + lname + "&username=" + username + "&email=" + email + "&password=" + password;
if(fname == "" || lname == "" || username == "" || email == "" || password == ""){
$('#message').html('Please fill in the blanks');
}else{
$.ajax ({
url: 'core/register.php?',
type:'post',
data: data,
success: function(data) {
$("#message").html(data);
}
});
}
});
}
</script>
and this is register.php
<?php
include_once "util.php";
session_start();
$util = new util();
$post = $_POST['data'];
$data = json_decode($post);
$result = $util->newUser($data);
if($result) {
echo 1;
}else {
echo 0;
}
and finally util.php
public function newUser($data){
// Our database object
$db = new dbhandler();
// Quote and escape form submitted values
$fname = $db -> quote($fname->fname);
$lname = $db -> quote($lname->lname);
$username = $db -> quote($username->username);
$email = $db -> quote($email->email);
$password = $db -> quote($password->password);
// Insert the values into the database
$result = $db -> query("INSERT INTO `users` (`fname`,`lname`,`username`,`email`,`password`) VALUES (" . $fname . "," . $lname . "," . $username . "," . $email . "," . $password . ");");
}
Almost! 2 problems though.
You are sending in the data as a url format, but you are reading it as a JSON format. Instead of
var data = "fname=" + fname + "&lname=" + lname + "&username=" + username + "&email=" + email + "&password=" + password;
You need to create an object with:
var data = array(
"fname": fname,
"lname": lname,
"username": username,
"email": email,
"password": password
}
You need to get the variables from inside the $data object you passed in.
public function newUser($data){
// Our database object
$db = new dbhandler();
// Quote and escape form submitted values
$fname = $db -> quote($data->fname);
$lname = $db -> quote($data->lname);
$username = $db -> quote($data->username);
$email = $db -> quote($data->email);
$password = $db -> quote($data->password);
// Insert the values into the database
$result = $db -> query("INSERT INTO `users` (`fname`,`lname`,`username`,`email`,`password`) VALUES (" . $fname . "," . $lname . "," . $username . "," . $email . "," . $password . ");");
}
Related
I am trying to store the form data into database using ajax but it doesn't shows any success neither any error.
Here is my code.
<form method="POST" id="add_user" name='reg' >
<fieldset>
<legend>Student information:-</legend>
<ul>
<li>
<label> FirstName: </label><input type="text" id="name" name="name" required>
<span id='error' style="display:none;color:red;"> Only alphabets </span>
</li>
<li>
<label> LastName: </label><input type="text" id="lname" name="lname" required>
<span id='error1' style="display:none;color:red;"> Only alphabets </span>
</li>
<li>
<label>Username:</label>
<input type="text" id="username" name="username"/>
< /li>
<li>
<label>Password:</label>
<input type="password" id="password" name="password"/>
</li>
<label>
Gender: </label>
<input type="radio" id='gender' name="gender" value="male" required> Male
<input type="radio" name="gender" id='gender' value="female" required> Female
<input type="radio" name="gender" id='gender' value="other" required> Other
<li>
<label>
Email: </label>
<input id="email" type="text" name="email" required>
<span id='error2' style="display:none;color:red;"> Invalid email </span>
</li>
<li>
<label> Mobile:</label>
<input id="mobile" type="text" maxlength="10" name="mobile" required >
<span id='error3' style="display:none;color:red;"> only digits </span>
</li>
<li>
address: <textarea name="address" type="text" rows="3" cols="40"> </textarea>
</li>
</ul>
<p><button class = 'button' type="submit" id='submit'>Add User</button></p>
</fieldset>
</form>
This form in which i enter any values it got stored into database.
Here is my js file which uses ajax function to send data inext file which stores the result into database
serve.js
$(document).ready(function(){
$(document).on('submit','#add_user',function(e){
var form_data = $('#add_user').serialize();
var request = $.ajax({
url: 'fun.php?job=add',
cache : false,
data : form_data,
dataType : 'json',
contentType : 'application/json; charset=utf-8',
type : 'get'
});
request.done(function(output){
if (output.result == 'success'){
var name = $('#fname').val();
show_message("User '" + name + "' added successfully.", 'success' );
}, true);
} else{
show_message('Add request failed','error');
};
});
});
fun.php
if ($job != ''){
// Connect to database
$db_connection = mysqli_connect($db_server, $db_username, $db_password, $db_name);
if (mysqli_connect_errno()){
$result = 'error';
$message = 'Failed to connect to database: ' . mysqli_connect_error();
$job = '';
}
if ($job == 'add'){
/ / Add user
$query = "INSERT INTO oops ";
if (isset($_GET['name'])) { $query .= "name = '" . mysqli_real_escape_string($db_connection, $_GET['name']) . "', "; }
if (isset($_GET['lname'])) { $query .= "lname = '" . mysqli_real_escape_string($db_connection, $_GET['lname']) . "', "; }
if (isset($_GET['username'])) { $query .= "username = '" . mysqli_real_escape_string($db_connection, $_GET['username']) . "', "; }
if (isset($_GET['password'])) { $query .= "password = '" . mysqli_real_escape_string($db_connection, $_GET['password']) . "', "; }
if (isset($_GET['gender'])) { $query .= "gender = '" . mysqli_real_escape_string($db_connection, $_GET['gender']) . "', "; }
if (isset($_GET['email'])) { $query .= "email = '" . mysqli_real_escape_string($db_connection, $_GET['email']) . "', "; }
if (isset($_GET['mobile'])) { $query .= "mobile = '" . mysqli_real_escape_string($db_connection, $_GET['mobile']) . "', "; }
if (isset($_GET['address'])) { $query .= "address = '" . mysqli_real_escape_string($db_connection, $_GET['address']) . "'"; }
$query = mysqli_query($db_connection, $query);
if (!$query){
$result = 'error';
$message = 'query error';
} else {
$result = 'success';
$message = 'query success';
}
}
// Close database connection
mysqli_close($db_connection);
}
// Prepare data
$data = array(
"result" => $result,
"message" => $message,
"data" => $mysql_data
);
// Convert PHP array to JSON array
$json_data = json_encode($data);
print $json_data;
?>
Am I missing something please help if you found any fault in my code.
because you are using post method in your form:
<form method="POST" id="add_user" name='reg' >
and trying to receive params via get:
isset($_GET['name'])
just use post method everywhere
and also in jQuery you need to set:
type: "POST"
I am not able to post data to MySql database. I am running the project on chrome browser(windows7). Here I can see the params but they are not sent to the database table. What actually is the problem with my code?
My php code is:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
$postdata = file_get_contents("php://input");
$email = $postdata->email;
$password = $postdata->password;
$username = $postdata->username;
$con = mysqli_connect("localhost","root",'') or die ("Could not connect: " . mysql_error());;
mysqli_select_db($con, 'db_lastLog');
$qry_em = 'select count(*) as cnt from users where email ="' . $email . '"';
$qry_res = mysqli_query($con, $qry_em);
$res = mysqli_fetch_assoc($qry_res);
if($res['cnt']==0){
$qry = 'INSERT INTO users (name,pass,email) values ("' . $username . '","' . $password . '","' . $email . '")';
$qry_res = mysqli_query($con, $qry);
if ($qry_res) {
echo "1";
} else {
echo "2";;
}
}
else
{
echo "0";
}
?>
My controller code is:
.controller('SignupCtrl', function($scope, $http) {
$scope.signup = function (userdata) {
var request = $http({
method: "POST",
url: "http://localhost/lastLog.php",
crossDomain : true,
data: {
username : userdata.username,
password : userdata.password,
email : userdata.email
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function(data) {
if(data == "1"){
$scope.responseMessage = "Successfully Created Account";
}
if(data == "2"){
$scope.responseMessage = "Cannot Create Account";
}
else if(data == "0") {
$scope.responseMessage = "Email Already Exist"
}
});
}
})
My html code is:
<ion-pane>
<ion-header-bar class="bar-positive">
<h2 class="title">SignUp</h2>
</ion-header-bar>
<ion-view view-title="SignUp" name="signup-view">
<ion-content class="has-header" ng-controller="SignupCtrl">
<div class="list list-inset">
<label class="item item-input">
<input class="form-control" type="text" ng-model="userdata.username" placeholder="Enter Username">
</label>
<label class="item item-input">
<input type="text" ng-model="userdata.email" placeholder="Enter Your Email">
</label>
<label class="item item-input">
<input class="form-control" type="password" ng-model="userdata.password" placeholder="Enter Your Password">
</label>
<button class="button button-block button-positive" ng-click="signup(userdata)">SignUp</button><br>
<span>{{responseMessage}}</span>
</div>
</ion-content>
</ion-view>
</ion-pane>
I am not able to connect to the database what should be the syntax when I have created the database (myDb) using phpMyAdmin. I have placed signup.php on the server i.e www folder.
Please point out if there is some other mistake I have made in this code.
signup.html:
<ion-header-bar class="bar-positive">
<h2 class="title">SignUp</h2>
</ion-header-bar>
<ion-view view-title="SignUp" name="signup-view">
<ion-content class="has-header">
<div class="list list-inset">
<label class="item item-input item-floating-label">
<span class="input-label">Enter Username</span>
<input class="form-control" type="text" ng-model="userdata.username" placeholder="Enter Username">
</label>
<label class="item item-input item-floating-label">
<span class="input-label">Enter Your Email</span>
<input type="text" ng-model="userdata.email" placeholder="Enter Your Email">
</label>
<label class="item item-input item-floating-label">
<span class="input-label">Enter Your Password</span>
<input class="form-control" type="password" ng-model="userdata.password" placeholder="Enter Your Password">
</label>
<button class="button button-block button-calm" ng-click="signUp(userdata)">SignUp</button><br>
<span>{{responseMessage}}</span>
</div>
</ion-content>
</ion-view>
signup.php:
<?php
header("Content-Type: application/json; charset=UTF-8");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email = $postdata->email;
$password = $postdata->password;
$username = $postdata->username;
$con = mysql_connect("localhost","root",'') or die ("Failed to connect to MySQL: " . mysql_error());;
mysql_select_db('myDb', $con);
$qry_em = 'select count(*) as cnt from users where email="' . $email . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
if($res['cnt']==0){
$qry = 'INSERT INTO users (name,password,email) values ("' . $username . '","' . $password . '","' . $email . '")';
$qry_res = mysql_query($qry);
if ($qry_res) {
echo "1";
} else {
echo "2";;
}
}
else
{
echo "0";
}
?>
app.js:
.controller('SignupCtrl', function($scope, $http) {
$scope.signup = function () {
var request = $http({
method: "post",
url: "http://localhost/signup.php",
crossDomain : true,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
username: $scope.userdata.username,
email: $scope.userdata.email,
password: $scope.userdata.password
},
});
request.success(function(data) {
if(data == "1"){
$scope.responseMessage = "Account Created Successfully!";
}
if(data == "2"){
$scope.responseMessage = "Can not Create Account";
}
else if(data == "0") {
$scope.responseMessage = "Email Already Exists"
}
});
}
});
use $request->email, $request->password, $request->username instead of $postdata->email, $postdata->password, etc...
If PHP is must, I would recommend looking at Slim Framework which is made for creating APIs.Some other solutions that fits here (probably better than PHP & MySQL for this purpose) are Mongo + Express or ParseSDK for JavaScript are something to look at as well. I would recommend Parse since it is very easy to get started with and remove a lot of back end headaches.
Sample example using ionic to access API:
Controller:
app.controller('AppCtrl', function($scope){
$http.get('API_URL')
.then(
function(data){
console.log(data);
$scope.data = data;
// JSON data returned as response
},
function(err){
console.log(err);
$scope.err = err;
// when error occurs
}
);
});
View:
<ion-content ng-controller="AppCtrl">
<div> {{ data }} {{ err }} </div>
</ion-content>
Example of usage of JSON data.
I'm trying to figure out why my data is not being collected by my PHP files.
This is my index.html
<!DOCTYPE html>
<html lang="en" ng-app="gemStore">
<head>
<meta http-equiv='Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' />
<title>Angular</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div ng-controller="custController">
<form>
First Name: <input type="text" ng-model="firstname"><br>
Last Name: <input type="text" ng-model="lastname"><br>
Choose Username: <input type="text" ng-model="username"><br>
Choose Password: <input type="text" ng-model="password"><br>
Address 1: <input type="text" ng-model="address1"><br>
Address 2: <input type="text" ng-model="address2"><br>
City: <input type="text" ng-model="city"><br>
State: <input type="text" ng-model="state"><br>
Zip: <input type="number" ng-model="zip"><br>
<input type="button" value="Submit" ng-click="insertdata()"><br>
</form>
</div>
<script src="js/angular.min.js"></script>
<script src="js/script.js"></script>
<script src="js/products.js"></script>
</body>
</html>
This is my script.js
(function(){
var app = angular.module('gemStore', ['store-products']);
app.controller('StoreController', ['$http', function($http){
var store = this;
store.products = [];
$http.get('/store-products.json').success(function(data){
store.products = data;
});
}]);
app.controller('custController', function($scope,$http){
$scope.insertdata = function(){
$http.post('insert.php',{'firstname':$scope.firstname,'lastname':$scope.lastname,'address1':$scope.address1,'address2':$scope.address2, 'city':$scope.city,'state':$scope.state,'zip':$scope.zip,'username':$scope.username,'password':$scope.password})
.success(function(data,status,headers,config){
console.log('data inserted successfully. First Name: ' + $scope.firstname);
});
}
});
})();
And finally my PHP file
<?php
$data = json_decode(file_get_contents("php://input"));
$firstname = mysql_real_escape_string($data->firstname);
$lastname = mysql_real_escape_string($data->lastname);
$username = mysql_real_escape_string($data->username);
$address1 = mysql_real_escape_string($data->address1);
$address2 = mysql_real_escape_string($data->address2);
$city = mysql_real_escape_string($data->city);
$state = mysql_real_escape_string($data->state);
$zip = mysql_real_escape_string($data->zip);
$password = mysql_real_escape_string($data->password);
mysql_connect("localhost","root","");
mysql_select_db("mydatabase");
mysql_query("INSERT INTO users (`firstname`, `lastname`, `username`, `password`, `address1`, `address2`, `city`, `state`, `zip`)VALUES('" . $firstname . "','" . $lastname . "','" . $username . "','" . $password . "','" . $address1 . "','" . $address2 . "','" . $city . "','" . $state . "','" . $zip . "')");
?>
I am thinking it has something to do with headers, but I'm not sure where I should add it or what needs to be changed. Any help would be appreciated. Thanks.
Also, I am using angular 1.3.16, but I doubt that makes a difference.
try this in your insertdata function.
$scope.insertdata = function(){
var data = {'firstname':$scope.firstname,'lastname':$scope.lastname,'address1':$scope.address1,'address2':$scope.address2, 'city':$scope.city,'state':$scope.state,'zip':$scope.zip,'username':$scope.username,'password':$scope.password};
$http({
url:'insert.php',
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data :data
}).success(function(data,status,headers,config){
console.log('data inserted successfully. First Name: ' + $scope.firstname);
});
}
I am trying to validate a captcha code field so if the code they enter is correct it will take them to a thank you page with the download link, but if the security code they entered is incorrect then they will see a sorry message and to return back to previous page.
The issue I am facing is when I enter the captcha into this field and click submit the data is always no.
My form is a as follows:
<form action="" name="downloadform" id="downloadform" class="downloadform" method="post">
<div class="field">
<input name="name" type="text" id="name" class="input name" placeholder="Name..." />
</div>
<div class="field">
<input name="company" type="text" id="company" class="input company" placeholder="Company..." />
</div>
<div class="field">
<input name="tel" type="text" id="tel" class="input tel" placeholder="Telephone..." />
</div>
<div class="field">
<input name="email" type="text" id="email" class="input email" placeholder="Email Address..." />
</div>
<div class="field">
<img src="/CaptchaSecurityImages.php" alt="Captcha" class="captcha" />
<input type="text" name="sec_code" id="sec_code" class="input sec_code" placeholder="Please enter the characters above" />
</div>
<div class="field">
<div class="medium secondary btn"><input type="submit" name="Submit2" value="Send Request" class="btn" id="downloadbtn" /></div>
<input type="hidden" name="product" id="product" class="product" value="<?php echo $page[3]; ?>" />
</div>
</form>
My ajax form file looks like this:
$(function() {
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$("#downloadbtn").click(function() {
var name = $("#name").val();
var company = $("#company").val();
var tel = $("#tel").val();
var email = $("#email").val();
var product = $("#product").val();
var sec_code = $("#sec_code").val();
if (name == "") {
$("#name").focus();
$("#name").val("");
$("#name").css({background:"#b72a18", color:"#fff"});
return false;
}
if (company == "") {
$("#company ").focus();
$("#company ").val("");
$("#company ").css({background:"#b72a18", color:"#fff"});
return false;
}
if (tel == "") {
$("#tel").focus();
$("#tel").val("");
$("#tel").css({background:"#b72a18", color:"#fff"});
return false;
}
if (!filter.test(email)) {
$("#email").focus();
$("#email").val("");
$("#email").css({background:"#b72a18", color:"#fff"});
return false;
}
if (product == "") {
$("#product").focus();
$("#product").val("");
$("#product").css({background:"#b72a18", color:"#fff"});
return false;
}
if (sec_code == "") {
$("#sec_code").focus();
$("#sec_code").val("");
$("#sec_code").css({background:"#b72a18", color:"#fff"});
return false;
}
$('.downloadform').html('<center><img src="/images/ajax-loader.gif" style="padding:20px;"></center>');
var dataString = '&name=' + name + '&tel=' + tel + '&company=' + company + '&email=' + email + '&product=' + product + '&sec_code=' + sec_code + '&type=download';
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/process_download.php",
data: dataString,
datatype: 'json',
success: function(data) {
$('.downloadform').html('<center><img src="/images/ajax-loader.gif" style="padding:20px;"></center>')
.hide()
.fadeIn(1500, function() {});
setTimeout(function ()
{
$(window.location).attr('href', '/process.php?download=' + data.product + '&sec_code=' + data.sec_code);
}, 2000);
}
});
return false;
});
});
Then I have my process download file:
<?php
session_start();
header("Content-type: application/json");
ob_start();
include('inc/connection.php');
$product = $_POST['product'];
$sec_code = $_SESSION['security_code'] == $_POST['sec_code'] ? 'yes' : 'no';
ob_end_clean();
$data = array('product'=>$product,'sec_code'=>$sec_code);
print json_encode($data);
die();
?>
Then the final process:
<?php
session_start();
include('inc/connection.php');
$sec_code = $_GET['sec_code'];
$proddownlink = $_GET['download'];
$proddownl = str_replace("_", " ", $_GET['download']);
$proddownl = ucwords($proddownl);
if ($sec_code == 'no') {
$message = '<p>Security code is wrong. Please click here to return back.</p>';
} else {
$message = '<p>Thank you for downloading ' . $proddownl . ' Data Sheet.</p>
<p>Please click here to download ' . $proddownl . ' PDF.</p>';
include_once('inc/connection.php');
include_once('inc/class.phpmailer.php');
$name = $_POST['name'];
$company = $_POST['company'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$product = $_POST['product'];
$sec_code = $_POST['sec_code'];
$type = $_POST['type'];
$bodytext = "<ul>
<li><strong>Name:</strong> $name</li>
<li><strong>Company:</strong> $company</li>
<li><strong>Telephone Number:</strong> $tel</li>
<li><strong>Email Address:</strong> $email</li>
<li><strong>Area of Interest:</strong> $product</li>
</ul>";
$subject = "New Enquiry";
$query = "insert into user_email set name = '$name', email = '$email', tel = '$tel', type = '$type', message = '$bodytext'";
$result = $conn->query($query);
if(!$result) die($conn->error);
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = $bodytext;
$mail->From = "sales#fidelitysystems.co.uk";
$mail->FromName = $name;
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
#$mail->AddAddress("sales#fidelitysystems.co.uk");
$mail->AddAddress("craig#arrivaldesign.co.uk");
$mail->IsSMTP();
$mail->SMTPAuth = "true";
$mail->Username = "postmaster#arrivalbusiness.co.uk";
$mail->Password = "edward";
$mail->Host = "mail.arrivalbusiness.co.uk";
$mail->Port = 587;
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
?>