Cannot post data to MySql database from my ionic app - php

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>

Related

it create a record but it is empty

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 . ");");
}

Form Data does not post duplicate data

I have this form
<form id="home" class="validate-form" method="post" enctype="multipart/form-data">
<!-- Form Item -->
<div class="form-group">
<label>How much money do you need? (Kenya Shillings)</label>
<div class="input-group">
<div class="input-group-addon">Ksh</div>
<input id="moneyAmount" type="number" id="amount" name="amount" class="form-control slider-control input-lg" value="100000" min="10000" max="1000000" data-slider="#moneySlider" required>
</div>
<div id="moneySlider" class="form-slider" data-input="#moneyAmount" data-min="10000" data-max="1000000" data-value="100000"></div>
</div>
<!-- Form Item -->
<div class="form-group">
<label>How long? (months)</label>
<div class="input-group">
<input id="monthNumber" type="number" id="duration" name="duration" class="form-control slider-control input-lg" value="10" min="6" max="12" data-slider="#monthSlider" required>
<div class="input-group-addon">months</div>
</div>
<div id="monthSlider" class="form-slider" data-input="#monthNumber" data-min="6" data-max="12" data-value="10"></div>
</div>
<div class="form-group">
<label>Telephone Number</label>
<!-- Radio -->
<input type="number" id="telephone" name="telephone" class="form-control" required/>
</div>
<!-- Form Item -->
<div class="form-group">
<label>3 Months Bank or Paypal or Mpesa Statements</label>
<!-- Radio -->
<input type="file" name="image" class="ml btn btn-primary btn-lg" /><span>Upload</span>
</div>
<!-- Form Item -->
<div class="form-group">
<label>Monthly repayment</label>
<span id="formResult" class="form-total">Ksh<span>262.99</span></span>
</div>
<div class="form-group form-submit">
<button type="submit" class="btn-submit btn-lg"><span>Send a request!
</span></button>
</div>
</form>
This is the Jquery Script.
$( "#home" ).on( "submit", function( event ) {
event.preventDefault();
alert('subsequent clicks');
function chek(fData) {
var reg = new RegExp("^[-]?[0-9]+[\.]?[0-9]+$");
return reg.test(fData)
}
var phone = $('#telephone').val();
var amount = $('#amount').val();
var duration = $('#duration').val();
var ch = chek(phone);
if(phone == ""){
alert('phone cannot be empty');
return;
}
if(amount == ""){
alert('amount cannot be empty');
return;
}
if(duration == ""){
alert('duration cannot be empty');
return;
}
if(ch == false){
alert("Phone number must be a number");
return;
}
if(phone.length < 10 || phone.length > 12 ){
alert("Phone number must have 10 digits");
return;
}
if(ch == true && phone !== "" && amount !== "" && duration !== "" && phone.length == 10){
var s = phone;
s = s.replace(/^0+/, '');
var cc = 254;
var p = cc+s;
var pn = p.toString();
$('#telephone').val(p.toString());
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://example.com/home.php', //<== just add it to the end of url ***
type: 'POST',
data: formData,
async: true,
success: function (data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
}
});
This is my PHP code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyz')
{
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$str .= $keyspace[random_int(0, $max)];
}
return $str;
}
$pass = random_str(4);
/**
Generic Customer Shown Interest
*/
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "algo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Posted Variables
$amount = $_POST['amount'];
$duration = $_POST['duration'];
$telephone = $_POST['telephone'];
$date = date('Y-m-d H:i:s');
//Check If User Exists
$result = $conn->query("select id from users where telephone=$telephone");
if($result->num_rows == 0) {
//Insert New User
$sql = "INSERT INTO users (telephone, password, service_name,date_submitted) VALUES ('$telephone', '$pass', 'loans','$date')";
if ($conn->query($sql) === TRUE) {
echo "User Is Inserted";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
//Insert New User
$sql2 = "INSERT INTO loans (amount, duration, telephone,documents,status,date)
VALUES ('$amount', '$duration','$telephone','logan2','on-hold','$date')";
if ($conn->query($sql2) === TRUE) {
echo "Loan Is Inserted";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
$conn->close();
}
?>
As you can tell the form is pretty basic and its only posting data to the server. When I load the page, I am able to insert data into the database but when I click the link again, nothing is inserted.
Is form data blocking me from posting duplicate data to the server?
change ajax part of your code and replace to this code shown below:
<script type="text/javascript">
$.ajax({
type:'POST',
url:'testing2.php',
data:new FormData($('#svf-form-4')[0]),
cache: false,
contentType: false,
processData: false,
success:function(msg){
$('#message').html(msg);
}
});
return false;
</script>
Hope it will work .
I cant explain what really worked but it seems clearing the form did allow for more post submission although i relied on this comment What does "async: false" do in jQuery.ajax()?
and this page What does "async: false" do in jQuery.ajax()? for inspiration.
This is the success callback
success: function (data) {
$("#home").trigger('reset');
console.log(data);
},

How to Send Email verification using angularjs and php?

I created registration form and corresponding controller and backend php code.
The registered data is storing correctly . But i am not reciving mail in my email id. Please help me with this..
My html Code
<div class="col-lg-6 col-lg-offset-3 well " style="margin-top:1em; background-color:black; ">
<h4 style="color:white; text-align:center;"> <strong> FILL UP REGISTRAION FORM </strong> </h4>
</div>
<div class="col-lg-6 col-lg-offset-3 well" style="margin-bottom:10em;">
<form name="register" ng-app="TempleWebApp" ng-controller="RegisterCtrl" ng-submit="SignUp(register.$valid)" novalidate>
<!-- First Name -->
<div class="form-group col-lg-6" ng-class="{ 'has-error' : register.fname.$invalid && (register.fname.$dirty || submitted)}">
<label>First Name</label>
<input class="form-control" type="text" name="fname" ng-model="fname" placeholder="First Name" ng-required="true">
<span class="help-block" ng-show="register.fname.$invalid && register.fname.$error.required && (register.fname.$dirty || submitted)">
First Name is required.</span>
</div>
<!-- Last Name -->
<div class="form-group col-lg-6" ng-class="{ 'has-error' : register.lname.$invalid && (register.lname.$dirty || submitted)}">
<label>Last Name</label>
<input class="form-control" type="text" name="lname" ng-model="lname" placeholder="Last Name" ng-required="true">
<span class="help-block" ng-show="register.lname.$invalid && register.lname.$error.required && (register.lname.$dirty || submitted)">
Last Name is required.</span>
</div>
<!-- City -->
<div class="form-group col-lg-6" ng-class="{ 'has-error' : register.city.$invalid && (register.city.$dirty || submitted)}">
<label>City</label>
<input class="form-control" type="text" name="city" ng-model="city" placeholder="City" ng-required="true">
<span class="help-block" ng-show="register.city.$invalid && register.city.$error.required && (register.city.$dirty || submitted)">
City is required.</span>
</div>
<!-- Gender -->
<div class="form-group col-lg-6" ng-class="{ 'has-error' : register.gender.$invalid && (register.gender.$dirty || submitted)}">
<label>Gender</label> <br>
<input type="radio" name="gender" ng-model="gender" value="male" ng-required="true"> Male
<input type="radio" name="gender" ng-model="gender" value="female" ng-required="true" style="margin-left:5em;"> Female
<span class="help-block" ng-show="register.gender.$invalid && register.gender.$error.required && (register.gender.$dirty || submitted)">
Gender is required.</span>
</div>
<!-- Email -->
<div class="form-group col-lg-12" ng-class="{ 'has-error' : register.email.$invalid && (register.email.$dirty || submitted)}">
<label>Email</label>
<input class="form-control" type="text" name="email" ng-model="useremail" placeholder="Email" ng-pattern="/^[^\s#]+#[^\s#]+\.[^\s#]{2,}$/" ng-required="true">
<span class="help-block" ng-show="register.email.$invalid && register.email.$error.required && (register.email.$dirty || submitted)">
Email is required.</span>
<span class="help-block" ng-show="register.email.$error.pattern">
Enter Valid Email .</span>
</div>
<!-- Password -->
<div class="form-group col-lg-6" ng-class="{ 'has-error' : register.password.$invalid && (register.password.$dirty || submitted)}">
<label>Password</label>
<input class="form-control" type="password" name="password" ng-model="userpassword" placeholder="Password" ng-required="true">
<span class="help-block" ng-show="register.password.$invalid && register.password.$error.required && (register.password.$dirty || submitted)">
Password is required.</span>
</div>
<!-- CONFIRM PASSWORD -->
<div class="form-group col-lg-6" ng-class="{ 'has-error' : register.confirmPassword.$invalid && (register.confirmPassword.$dirty || submitted)}">
<label>Confirm Password</label>
<input type="Password" name="confirmPassword" class="form-control" ng-model="confirmPassword" placeholder="Confirm Your Password" ng-compare="password" ng-required="true">
<p ng-show="register.confirmPassword.$error.required && (register.confirmPassword.$dirty || submitted)" class="help-block">confirm password is required.</p>
<p ng-show="register.confirmPassword.$error.compare && (register.confirmPassword.$dirty || submitted)" class="help-block">Confirm password doesnot match.</p>
</div>
<div class="col-lg-12 well " ng-repeat="error in errors" style="background-color:red; margin-top:0.5em;"> {{ error}} </div>
<div class="col-lg-12 well" ng-repeat="msg in msgs" style="margin-top:0.5em;">
<h5 style="color:green;">{{ msg}} </h5>
</div>
<button type="submit" class="btn btn-success col-lg-12">
<span ng-show="searchButtonText == 'REGISTERING'"><i class="glyphicon glyphicon-refresh spinning"></i></span>
{{ searchButtonText }}
</button>
</form>
</div>
My controller
app.controller('RegisterCtrl', function ($scope,$location, $http,$timeout) {
$scope.gender = '';
$scope.errors = [];
$scope.msgs = [];
$scope.searchButtonText = "REGISTER DETAILS";
$scope.test = "false";
$scope.SignUp = function(isValid) {
// Set the 'submitted' flag to true
$scope.submitted = true;
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
if (isValid) {
$http.post('php/register.php',
{ 'fname': $scope.fname,
'lname': $scope.lname,
'city': $scope.city,
'gender': $scope.gender,
'pswd' : $scope.userpassword,
'email': $scope.useremail
})
.success(function(data, status, headers, config) {
if (data.msg != '')
{
$scope.msgs.push(data.msg);
$scope.test = "true";
$scope.searchButtonText = "REGISTERING";
//var goTopayment = function() { $scope.searchButtonText = "REGISTER DETAILS"; $location.path('/login'); };
// $timeout(goTopayment, 3000);
}
else
{
$scope.errors.push(data.error);
}
})
.error(function(data, status) { // called asynchronously if an error occurs or server returns response with an error status.
$scope.errors.push(status);
});
} // closing bracket for IF(isvalid)
} // closing bracket for $scope.SIGNUP = function
}); // closing bracket for register
My php Code is
<?php
$data = json_decode(file_get_contents("php://input"));
$fname = mysql_real_escape_string($data->fname);
$lname = mysql_real_escape_string($data->lname);
$city = mysql_real_escape_string($data->city);
$gender = mysql_real_escape_string($data->gender);
$upswd = mysql_real_escape_string($data->pswd);
$uemail = mysql_real_escape_string($data->email);
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('registraion', $con);
$qry_em = 'select count(*) as cnt from users where Email ="' . $uemail . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
if($res['cnt']==0){
$qry = 'INSERT INTO users (Firstname,Lastname,City,Gender,Password,Email) values
("' . $fname . '","' . $lname . '","' . $city . '","' . $gender . '","' . $upswd . '","' . $uemail . '")';
$qry_res1 = mysql_query($qry);
if (!$qry_res1) {
die('Invalid query: ' . mysql_error());
} else {
return mysql_insert_id();
}
$current_id = mysql_insert_id(); //last insert id
if(!empty($current_id)) {
$actual_link = "http://localhost/angular/php/"."activate.php?uid=" . $current_id;
$EmailTo = $uemail ;
$Subject = "User Registration Activation Email";
$Content = "Click this link to activate your account. <a href='" . $actual_link . "'>" . $actual_link . "</a>";
$MailHeaders = "From: Admin\r\n";
$success = mail($EmailTo, $Subject, $Content, $MailHeaders);
if($success ) {
$arr = array('msg' => "You have registered and the activation mail is sent to your email. Click the activation link to activate you account.", 'error' => '');
$jsn = json_encode($arr);
print_r($jsn);
}
}
}
else
{
$arr = array('msg' => "", 'error' => 'User Already exists with same email');
$jsn = json_encode($arr);
print_r($jsn);
}
?>
Finally I solved it. The problem was finding last inserted id value for $current_id variable.Since i was not getting correct value for this variable, value for $Emailto variable is not assigned with email id. So I changed php code to following way.
<?php
$data = json_decode(file_get_contents("php://input"));
$fname = mysql_real_escape_string($data->fname);
$lname = mysql_real_escape_string($data->lname);
$city = mysql_real_escape_string($data->city);
$gender = mysql_real_escape_string($data->gender);
$upswd = mysql_real_escape_string($data->pswd);
$uemail = mysql_real_escape_string($data->email);
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('registraion', $con);
$qry_em = 'select count(*) as cnt from users where Email ="' . $uemail . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);
if($res['cnt']==0){
$qry = 'INSERT INTO users (Firstname,Lastname,City,Gender,Password,Email) values
("' . $fname . '","' . $lname . '","' . $city . '","' . $gender . '","' . $upswd . '","' . $uemail . '")';
$qry_res1 = mysql_query($qry);
//changed current_id value finding method.
$current_id = mysql_query("select uid from users ORDER BY uid DESC LIMIT 1"); //last insert id
if(!empty($current_id)) {
$actual_link = "http://localhost/angular/php/"."activate.php?uid=" . $current_id;
$EmailTo = $uemail;
$Subject = "User Registration Activation Email";
$Content = "Click this link to activate your account. <a href='" . $actual_link . "'>" . $actual_link . "</a>";
$MailHeaders = "From: Admin\r\n";
if(mail($EmailTo, $Subject, $Content, $MailHeaders) ) {
$arr = array('msg' => "You have registered and the activation mail is sent to your email. Click the activation link to activate you account.", 'error' => '');
$jsn = json_encode($arr);
print_r($jsn);
}
}
}
else
{
$arr = array('msg' => "", 'error' => 'User Already exists with same email');
$jsn = json_encode($arr);
print_r($jsn);
}
?>

store the data into database through php form

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"

How to connect my ionic app with MySQL database?

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.

Categories