How to Send Email verification using angularjs and php? - 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);
}
?>

Related

My code doesn't insert into the database because of my form validation

Each time I use the method below to insert my form into the database, it doesn't do anything...
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post" class="form-horizontal">
<div class="form-group">
<label for="first_name" class="col-sm-4 control-label" >First Name:</label>
<div class="col-sm-8">
<input type="text" name="first_name" class="form-control" id="first_name" value="<?= $first_name; ?>"/>
<span id="error-msg"><?= $first_name_error; ?></span>
</div>
</div>
<div class="form-group">
<label for="last_name" class="col-sm-4 control-label">Last Name:</label>
<div class="col-sm-8">
<input type="text" name="last_name" class="form-control" maxlength="30" id="last_name" value="<?= $last_name; ?>"/>
<span id="error-msg"><?= $last_name_error; ?></span>
</div>
</div>
<div class="form-group">
<label for="email_address" class="col-sm-8 control-label">Email Address:</label>
<div class="col-sm-8">
<input type="text" name="email_address" class="form-control" id="email_address" placeholder="abc#email.com" value="<?= $email_address; ?>"/>
<span id="error-msg"><?= $email_address_error; ?></span>
</div>
</div>
<div class="form-group">
<label for="user_name" class="col-sm-4 control-label" >Username:</label>
<div class="col-sm-8">
<input type="text" name="username" class="form-control" maxlength="30" id="user_name" value="<?= $username; ?>"/>
<span id="error-msg"><?= $username_error; ?></span>
</div>
</div>
<div class="form-group">
<label for="country" class="col-sm-4 control-label">Phone:</label>
<div class="col-sm-8">
<input type="tel" id="phone" name="phone" class="form-control" value="<?= $phone; ?>"/>
<span id="valid-msg" class="hide">► </span>
<span id="error-msg" class="hide"><?= $phone_error; ?></span>
</div>
</div>
<div class="form-group">
<label for="pass_word" class="col-sm-4 control-label" >Password:</label>
<div class="col-sm-8">
<input type="password" name="password" class="form-control" maxlength="30" id="password" value="<?= $password; ?>"/>
<span id="error-msg"><?= $password_error; ?></span>
</div>
</div>
<div class="form-group">
<label for="confirm_password" class="col-sm-4 control-label" >Confirm password:</label>
<div class="col-sm-8">
<input type="password" name="confirm_password" class="form-control" maxlength="30" id="confirm_password" value="<?= $confirm_password; ?>"/>
<span id="error-msg"><?= $confirm_password_error; ?></span>
</div>
</div>
<div class="col-sm-8 col-sm-push-3">
<input type="submit" name="submit" class="btn bg-success" value="Register" onClick="return confirm('Are you sure your details are correct?');" />
</div>
</form>
<?php
//define variables and set them to empty values
$first_name = $last_name = $country = $phone = $email_address = $username = $password = $confirm_password = "";
$first_name_error = $country_error = $last_name_error = $phone_error = $email_address_error = $username_error = $password_error = $confirm_password_error = "";
$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
//form is submitted with post method
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["first_name"])){
$first_name_error = "<div class=''>First Name is required</div>";
}else{
$first_name = test_input($_POST["first_name"]);
//Check if name only contains letters and whitespaces
if(!preg_match("/^[a-zA-Z ]*$/",$first_name)){
$first_name_error = "<div class=''>Only letters and white space allowed</div>";
}
}
if(empty($_POST["last_name"])){
$last_name_error = "<div class=''>Last Name is required</div>";
}else{
$last_name = test_input($_POST["last_name"]);
//Check if name only contains letters and whitespaces
if(!preg_match("/^[a-zA-Z ]*$/",$last_name)){
$last_name_error = "<div class=''>Only letters and white space allowed</div>";
}
}
if(empty($_POST["email_address"])){
$email_address_error = "<div class=''>Email is required</div>";
}else{
$email_address = test_input($_POST["email_address"]);
// check if email address is well formed
if(!filter_var($email_address, FILTER_VALIDATE_EMAIL)){
$email_address_error = "<div class='btn bg-warning'>Invalid email format</div>";
}elseif($email_address = test_input($_POST["email_address"])){
$sql = "SELECT email_address FROM customers WHERE email_address = '$email_address'";
$mail = $database->query($sql);
if(mysqli_num_rows($mail) > 0){
$email_address_error = '<div class="">ERROR: Email already exists please use another email</div>';
}
}
}
if(empty($_POST["username"])){
$username_error = "<div class=''>Username is required</div>";
}else {
$username = test_input($_POST["username"]);
//check if username is atleast 7 characters
if(!preg_match("/^(?=.*?[a-z]).{7,}$/",$username)){
$username_error = "<div class=''>Username must be atleast 7 characters</div>";
}elseif($username = test_input($_POST["username"])){
$sql = "SELECT username FROM customers WHERE username = '$username'";
$user = $database->query($sql);
if(mysqli_num_rows($user) > 0){
$username_error = '<div class="">ERROR: Username already exists please use another username</div>';
}
}
}
if(empty($_POST["phone"])){
$phone_error = "<div class=''>Phone is required</div>";
}else {
$phone = test_input($_POST["phone"]);
}
if(empty($_POST["password"])){
$password_error = "<div class=''>Password is required</div>";
}else{
$password = test_input($_POST["password"]);
//check if password is atleast 7 characters
if(!preg_match("/^(?=.*?[a-z]).{7,}$/",$password)){
$password_error = "<div class=''>Password must be atleast 7 characters</div>";
}
}
if(empty($_POST["confirm_password"])){
$confirm_password_error = "<div class=''>Alternate password is required</div>";
}else{
$confirm_password = test_input($_POST["confirm_password"]);
//check if cpassword is atleast 8 characters
if(!preg_match("/^(?=.*?[a-z]).{7,}$/",$confirm_password)){
$confirm_password_error = "<div class=''>Password must be atleast 7 characters</div>";
}else{
if($_POST['confirm_password'] != $password){
$confirm_password_error = "<div class=''>Password does not match!!!</div>";
}
}
}
if($first_name_error = "" and $last_name_error = "" and $mobile_number_error = "" and $email_address_error = "" and $username_error = "" and $password_error = "" and $confirm_password_error = ""){
$str = '1234567890asdf';
$str = str_shuffle($str);
$str = substr($str, 0, 10);
$token = 'vfjhvbkebecbjDRCWVJEcbkrvlnke24tir7c_zdvbejw968';
$token = str_shuffle($token);
$token = substr($token, 0, 10);
$user = new Customer_reg();
$password = sha1($password);
$user->customer_id = $str;
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->email_address = $email_address;
$user->username = $username;
$user->password = $password;
$user->mobile_number = $phone;
$user->created_at = $timestamp;
$user->updated_at = $timestamp;
$user->emailConfirm = 0;
$user->token = $token;
$user->str = $str;
if($user->save()){
$mail = new Mail();
$mail->email_address = $email_address;
$mail->token = $str;
$mail->send_verification();
$session->message('<div class="btn bg-success">Account created sucessfully please verify your email.</div>');
redirect_to('login.php');
}
}
if(empty($_POST["message"])){
$message = "";
} else{
$message = test_input($_POST["message"]);
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = htmlentities($data);
return $data;
}
?>
I realized my code has a bug from
if($first_name_error = "" and $last_name_error = "" and $mobile_number_error = "" and $email_address_error = "" and $username_error = "" and $password_error = "" and $confirm_password_error = "")
Please, how do I modify this? All my functions and every other code works perfectly okay apart from the above.
First of all, you should be using '==' here, not '=', and "&&" not "and".
I.e. change this:
if($first_name_error = "" and $last_name_error = "" and $mobile_number_error = "" and $email_address_error = "" and $username_error = "" and $password_error = "" and $confirm_password_error = "") { }
to this:
if($first_name_error == "" && $last_name_error == "" && $mobile_number_error == "" && $email_address_error == "" && $username_error == "" && $password_error == "" && $confirm_password_error == "") { }
Ensure you define $mobile_number_error and try executing your codes again and see.

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"

Inserting angularjs form values into database using php

I have created angularjs form. I want to store the form values into data base using PHP and before inserting I want to check weather the email is already exists or not. I am new to PHP. Any help would be appreciated. Thanks.
Register.html:
<div class="container col-lg-10" style="margin-top:2em; margin-left:2em;" >
<div class="panel panel-default">
<div class="panel-body" ng-app="TempleWebApp" ng-controller="RegisterCtrl">
<form name="userForm" ng-submit="submitForm()" novalidate>
<!-- NAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && (userForm.name.$dirty || submitted)}">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="user.name" placeholder="Your Name" ng-required="true">
<p ng-show="userForm.name.$error.required && (userForm.name.$dirty || submitted)" class="help-block">You name is required.</p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && (userForm.email.$dirty || submitted)}">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="user.email" placeholder="Your Email Address" ng-required="true">
<p ng-show="userForm.email.$error.required && (userForm.email.$dirty || submitted)" class="help-block">Email is required.</p>
<p ng-show="userForm.email.$error.email && (userForm.email.$dirty || submitted)" class="help-block">Enter a valid email.</p>
</div>
<!-- PASSWORD -->
<div class="form-group" ng-class="{ 'has-error' : userForm.password.$invalid && (userForm.password.$dirty || submitted)}">
<label>Password</label>
<input type="Password" name="password" class="form-control" ng-model="user.passwrd" placeholder="Your Password" ng-required="true">
<p ng-show="userForm.password.$error.required && (userForm.password.$dirty || submitted)" class="help-block">Your password is required.</p>
</div>
<!-- TERMS & CONDITIONS -->
<div class="form-group" ng-class="{ 'has-error' : userForm.terms.$invalid && (userForm.terms.$dirty || submitted)}">
<label>Accept Terms & Conditions</label>
<input type="checkbox" value="" name="terms" ng-model="user.terms" ng-required="true" />
<p ng-show="userForm.terms.$error.required && (userForm.terms.$dirty || submitted)" class="help-block">Accept terms & conditions.</p>
</div>
<!-- ng-disabled FOR ENABLING AND DISABLING SUBMIT BUTTON -->
<!--<button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Register</button>-->
<button type="submit" class="btn btn-primary col-lg-offset-6">Register</button>
</form>
<pre>{{user}}
</pre>
</div>
</div>
</div>
Main.js:
var app = angular.module('TempleWebApp', [ 'ngRoute']);
app.controller('RegisterCtrl', function ($scope,$location, $http) {
$scope.user = {};
$scope.user.name= "" ;
$scope.user.email ="";
$scope.user.passwrd="";
$scope.user.terms="";
// function to submit the form after all validation has occurred
$scope.submitForm = function () {
// Set the 'submitted' flag to true
$scope.submitted = true;
$http.post("register.php",{'username':$scope.user.name,'email':$scope.user.email,'password':$scope.user.passwrd})
.success(function(data,status,headers,config){
console.log("Inserted Successfully!");
});
};
});
PHP code.
<?php
$data = json_decode(file_get_contents("php://input"));
$username = $data->username;
$email = $data->email;
$password = $data->password;
$con = mysql_connect("localhost","root","");
mysql_select_db("userregister");
$sql = "insert into user(username,email,password) values($username,'$email','$password')";
$result = mysql_query($sql);
?>
Try using mysqli in the following manner (Also note you should create the variable $dbname and assign the right dbname to it:
$data = json_decode(file_get_contents("php://input"));
$username = #$data->username;
$email = #$data->email;
$password = #$data->password;
$dbname = '';
$conn = new mysqli("localhost","root","",$dbname);
$check = "SELECT * FROM user WHERE email='$email'";
//The following rows check whether this email already exists in the DB
$results = $conn->query($check);
if($results && mysqli_num_rows($results)>0)
{
echo "email";
die;
}
//The following rows will work only if there is no such email in the DB
if($conn->connect_error)
{
echo "false";
die;
}
$sql = "INSERT INTO user VALUES values($username,'$email','$password')";
if ($conn->query($sql) === true)
{
echo "true";
}
You will also need to change your Javascript to fit the possible events:
$http.post("register.php",{'username':$scope.user.name,'email':$scope.user.email,'password':$scope.user.passwrd})
.success(function(data,status,headers,config){
if(data == 'true'){
console.log("Inserted Successfully!");
}
else if(data == 'email'){
console.log("The email already exists");
}
else{
console.log("There was an issue connecting to the DB");
}
});

PHP Form update without logout

As i am newbie to PHP kindly pardon me if i looks silly ,
I created a form in php , while i do the update part of the form the update reflects in db whereas in the form it still shows the same old value . i tried refresh and force refresh but nothing changes .
Whereas if i logout and login again , the form shows the updated value .
I tried using die(); after mysql_close($link); but it logs out the session and needs to re-login .
Kindly help me on viewing the changes while i am still inside the login .
My code is as follows :
<?php
if(isset($_POST['update'])) {
$name_a = $_POST['name'];
$email_a = $_POST['email'];
$pass_a = $_POST['password'];
$sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' ";
$retval = mysql_query($sql,$link);
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($link);
}else {
?>
<!-- Widget: user widget style 1 -->
<div class="box box-widget widget-user-2">
<!-- Add the bg color to the header using any of the bg-* classes -->
<div class="widget-user-header bg-yellow">
<div class="widget-user-image">
<?php echo '<img src="' . $img . '" class="img-circle" alt="User Image">'; ?>
</div>
<!-- /.widget-user-image -->
<h3 class="widget-user-username"><?php echo "$name"; ?></h3>
<h5 class="widget-user-desc"><?php echo "$role"; ?></h5>
</div>
<div class="box-footer no-padding">
<form role="form" method = "post" action = "<?php $_PHP_SELF ?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo "$name"; ?>">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo "$email"; ?>">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo "$password"; ?>">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" id="update" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
<!-- /.widget-user -->
<?php
}
?>
SOLUTION
1) use the updated value like $name_a instead of $name because $name_a contain updated value and $name contain old value
2) reload page after update and get new value from database on page load and store that value in $name , $email etc variable (if new data update successfully in database then only you get new value )
3) if You store your data in session or cookie then update session and cookie value also when you update in database
Try this:
<?php
$name = '';
$email = '';
$password = '';
$update_id = '';
//$img = '';
//$role = '';
//$link = null;
if(
isset($_POST['update']) &&
isset($_POST['id']) &&
isset($_POST['name']) &&
isset($_POST['email']) &&
isset($_POST['password'])
) {
$update_id = mysql_real_escape_string($_POST['id']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$sql = 'UPDATE admin SET a_name = \'' . $name . '\', a_email = \'' . $email . '\', password = \'' . $password . '\' WHERE aid = \'' . $update_id . '\'';
$result = #mysql_query($sql, $link);
if(!$result)
die('Could not update data: ' . mysql_error($link));
echo 'Updated data successfully', "\n";
}
elseif(isset($_GET['id'][0])) {
$update_id = mysql_real_escape_string($_GET['id']);
$sql = 'SELECT a_name,a_email,a_password FROM admin WHERE aid = \'' . $update_id . '\'';
$result = #mysql_query($sql, $link);
if($result) {
$result = mysql_fetch_row($result);
$name = $result[0];
$email = $result[1];
$password = $result[2];
}
else {
echo 'Could not find the id.' . "\n";
$update_id = '';
}
}
unset($result);
if(isset($update_id[0])) {
mysql_close($link);
?>
<!-- Widget: user widget style 1 -->
<div class="box box-widget widget-user-2">
<!-- Add the bg color to the header using any of the bg-* classes -->
<div class="widget-user-header bg-yellow">
<div class="widget-user-image">
<img src="<?php echo htmlspecialchars($img); ?>" class="img-circle" alt="User Image">
</div>
<!-- /.widget-user-image -->
<h3 class="widget-user-username"><?php echo htmlspecialchars($name); ?></h3>
<h5 class="widget-user-desc"><?php echo htmlspecialchars($role); ?></h5>
</div>
<div class="box-footer no-padding">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="hidden" name="id" value="<?php echo htmlspecialchars($update_id); ?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo htmlspecialchars($name); ?>">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo htmlspecialchars($email); ?>">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo htmlspecialchars($password); ?>">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" id="update" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
<!-- /.widget-user -->
<?php }
else {
$sql = 'SELECT aid,a_name FROM admin';
$result = #mysql_query($sql, $link);
if($result) {
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '' . $row['a_name'] . '<br />' . "\n";
}
}
mysql_close($link);
}
?>
As #DivyeshSavaliya mentioned in the comment the issue is ,
I didn't Used Select query after update . Once done that the issue solved
The new working code is
<?php
if(isset($_POST['update'])) {
$name_a = $_POST['name'];
$email_a = $_POST['email'];
$pass_a = $_POST['password'];
$sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' ";
$retval = mysql_query($sql,$link);
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
}
$result = mysql_query("SELECT * FROM admin where aid='$update_id' ",$link);
while($row = mysql_fetch_array($result)){
$name = $row['a_name'];
$email = $row['a_email'];
$password = $row['password'];
}
mysql_close($link);
?>
Thanks to #DivyeshSavaliya

Cannot post data to MySql database from my ionic app

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>

Categories