Ionic send empty records to mysql - php

I am trying to send data from my ionic app to mysql. The problem is when I click on the submit button, it actually post empty records in the database.
My HTML code
<form >
<label class="item item-input">
<span class="input-label">Product Name:</span>
<input type="text" ng-model="productname">
</label>
<label class="item item-input">
<span class="input-label">Product Price:</span>
<input type="number" ng-model="productprice" >
</label>
<label class="item item-input">
<span class="input-label" >Description:</span>
<input type="text" ng-model="productdescription">
</label>
<input type="button" value="Submit" class="button button-assertive button-block" ng-click="submit()">
</form>
The controller for the project
App.controller('appCtrl', ['$scope', '$http', '$state, function ($scope,
$http, $state, $ionicPopup, $timeout) {
$scope.submit = function (){
var link = "http://localhost/api.php";
$http.post(link, {
'productname' : $scope.productname,
'productprice' : $scope.productprice,
'productdescription' : $scopeproduct.description,
}).success(function(response){
$scope.pdata= response;
console.log(response);
//console.log(response);
})
}
}]);
This is my PHP code to post the the data to database
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "", "ionic");
if ($conn->connect_error) {
die("Connection failed: " .$conn->connect_error);
}
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata))
{
$request = json_decode($postdata);
$pname = $request->productname;
$pprice = $request->productprice;
$pdescription = $request->productdescription;
$sql = ("INSERT INTO `users` ( product_name, product_price, description) VALUES ('$pname', '$pprice', '$pdescription')");
mysqli_query($conn, $sql);
}
?

Related

Inserting form data from Ionic to MySQL DB doesn't work

Well, I am trying to insert data from an Ionic form to an MySQL database using a PHP server, i've followed this tutorial.
But when I try to insert data on the database it doesn't work.
Here's the code:
insertProdutos.html
<ion-view title="Products" id="page4" class=" " ng-controller="DataCtrl">
<ion-content padding="true" class="has-header">
<form id="form-promocao" class="list " ng-submit="submit()">
<p id="" style="margin-top:3px;color:#44729C;text-align:center;" class=" ">Entre com as informações do produto</p>
<ion-list id="cadastro-promocao" class=" ">
<label class="item item-input " id="codigoDoProduto">
<input type="number" placeholder="Codigo de barras..." ng-model="data.codigo">
</label>
<label class="item item-input " id="nomeDoProduto">
<input type="text" placeholder="Nome do produto..."ng-model="data.nome_produto">
</label>
<label class="item item-input " id="tipo_comercializacao">
<input type="text" placeholder="Tipo de comercializacao..."ng-model="data.tipo_comercializacao">
</label>
<label class="item item-input " id="Medida">
<input type="number" placeholder="Medida..." ng-model="data.medida">
</label>
<label class="item item-input " id="Peso">
<input type="number" placeholder="Peso..." ng-model="data.peso">
</label>
<input class="button button-block button-positive"
type="submit" name="submit" value="Submit to server" >
</ion-list>
</form>
</ion-content>
</ion-view>
controllers.js
.controller('DataCtrl', function($scope, $http) {
$scope.data = {};
$scope.submit = function(){
var link="http://localhost/PHPserver/api.php"
$http.post(link, {id_produto: $scope.data.codigo, nome_produto: $scope.data.nome_produto, medida_produto: $scope.data.medida, peso_produto: $scope.data.peso, tipo_comercializacao: $scope.data.tipo_comercializacao}).then(function (res){
$scope.response = res.data;
});
};
});
api.php
<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:
{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
include("connect.php");
$request = json_decode($postdata);
$codigo = $request->codigo;
$produto = $request->nome_produto;
$medida = $request->medida;
$tipoComercializacao= $request->tipo_comercializacao;
$peso = $request->peso;
$sql="INSERT INTO produto(id_produto, nome_produto,peso,tipo_comercializacao,valor_medida) VALUES('".$codigo."','".$produto."','".$peso."','".$tipoComercializacao."','".$medida."')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
When I insert the data on the form and press "Submit to server", nothing happens, it doesn't submit and I get no erros on console log.
I would appreciate some help here.
Thank you :)

mysqli_prepare do not work right

I want to INSERT a few records in my tabel, for this I use mysqli_prepare, bind_param and execute.
In element inspection he gives a 500 internal server error in the params he gives all the data I need.
I hope you guys can help me, here is my code:
PHP
<form id="addFolder">
<div class="form-group col-md-6">
<label for="folderName">Map naam</label>
<input type="text" class="form-control" id="folderName" placeholder="Map naam">
</div>
<div class="form-group col-md-6">
<label for="selectRootFolder">Selecteer root map</label>
<select class="form-control" id="selectRootFolder">
<?php
getRootFolders();
?>
</select>
</div>
<div class="form-group col-md-6">
<label for="selectIcon">Selecteer icon <span class="fa fa-question-circle" id="fa-ask"></span></label>
<input type="text" class="form-control" id="selectIcon" placeholder="fa fa-icon">
</div>
<br><br><br>
<div class="form-group col-md-4">
<div class="checkbox">
<label>
<input type="checkbox" id="isRootMap"> Is root map
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="active"> Actief
</label>
</div>
</div>
<input type="submit" class="btn btn-info" value="Voeg toe" style="float:right; margin-top: 4%;">
</form>
jQuery
$("#addFolder").on("submit", function(e) {
e.preventDefault();
var folderName = $("#folderName").val();
var rootId = $("#selectRootFolder").find("option:selected").data("id");
var isRoot = $("#isRootMap").is(":checked");
var icon = $("#selectIcon").val();
var active = $("#active").is(":checked");
var array = [folderName, rootId, isRoot, icon, active];
$.ajax({
method: "POST",
url: "../admin/handlers/addFolderHandler.php",
data: { data: array }
}).done(function(data) {
if (data == true)
{
window.location.href = "index.php";
}
});
});
Handler
<?php
$gegevens = $_POST['data'];
$folderName = $gegevens[0];
$rootId = ($gegevens[3] == true) ? NULL : $gegevens[1];
$isRoot = ($gegevens[3] == true) ? 1 : 0;
$icon = ($gegevens[3] == true) ? $gegevens[4] : "";
$active = ($gegevens[5] == true) ? "1" : "0";
if (addNewFolder($rootId, $isRoot, $folderName, $icon, $active))
{
echo true;
}
else
{
echo false;
}
?>
Function
function addNewFolder($rootId, $isRoot, $folderName, $icon, $active)
{
global $con;
$query = mysqli_prepare($con, "INSERT INTO folders (parent_id, is_root, `name`, icon, active) VALUES (?, ?, ?, ?, ?)");
$query->bind_param('ddssi', $rootId, $isRoot, $folderName, $icon, $active);
if ($query->execute())
{
return true;
}
else
{
return false;
}
}

Unable to post data to database using Ionic

I am trying to gain some experience with creating an Ionic app. In my app, I have created a registration form.
register.html
<form ua-signup ng-controller="registerCtrl">
<ion-view title="Sign Up">
<ion-content>
<div class="list list-inset">
<label class="item item-input">
<span class="input-label">ID</span>
<input type="text" ng-model="data.id">
</label>
<label class="item item-input">
<span class="input-label">First Name</span>
<input type="text" ng-model="data.fname">
</label>
<label class="item item-input">
<span class="input-label">Last Name</span>
<input type="text" ng-model="data.lname">
</label>
<label class="item item-input">
<span class="input-label">Email</span>
<input type="text" ng-model="data.email" ua-is-email>
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" ng-model="data.pass">
</label>
<label class="item item-input">
<span class="input-label">Mobile No.</span>
<input type="tel" ng-model="data.tel">
</label>
<label class="item item-input item-select">
<div class="input-label" ng-model="data.course">
Course
</div>
<select>
<option selected>HUBIT</option>
<option>HUBMC</option>
<option>HUBIM</option>
<option>HUBGM</option>
</select>
</label>
<label class="item item-input">
<div class="input-label">
Subject
</div>
<select multiple="multiple">
<option selected>HUBIT</option>
<option>HUBMC</option>
<option>HUBIM</option>
<option>HUBGM</option>
</select>
</label>
</div>
<div class="padding">
<button type="submit" class="button button-block button-positive" ng-click="Register(data);">
<span ng-show="!loading">Create Account</span>
<i ng-show="loading" class="ion-loading-b"></i>
</button>
</div>
</ion-content>
</ion-view>
<div class="bar bar-footer bar-assertive" ng-show="error">
</div>
</form>
controller.js
app.controller('registerCtrl', function($scope,$http,$state) {
$scope.user = {};
$scope.register = function(data){
$scope.id = $scope.data.id;
$scope.fname = $scope.data.fname;
$scope.lname = $scope.data.lname;
$scope.email = $scope.data.email;
$scope.pass = $scope.data.pass;
$scope.tel = $scope.data.tel;
$scope.course = $scope.data.course;
$http.post("http://localhost:81/fyp/register.php",{
'id':$scope.id,
'fname':$scope.fname,
'lname':$scope.lname,
'email':$scope.email,
'pass':$scope.pass,
'tel':$scope.tel,
'course':$scope.course
})
.success(function(data, status, headers, config){
console.log("data inserted");
})
$state.go('tab.dash');
}
});
And my register.php which is on a xampp server
?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$id = mysql_real_escape_string($request->id);
$fname = mysql_real_escape_string($request->fname);
$lname = mysql_real_escape_string($request->lname);
$password = mysql_real_escape_string($request->pass);
$email = mysql_real_escape_string($request->email);
$phone = mysql_real_escape_string($request->tel);
$course = mysql_real_escape_string($request->course);
// Connect to MySQL
$db = mysql_connect("localhost","root","");
if (!$db) {
die("Could not connect to database </body></html>");
};
// open a9963146_fyp16 database
$db_select = mysql_select_db('fyp',$db);
if (!$db_select) {
die("Could not connect to database </body></html>");
};
if($id != '' && $lname != '' & $password != '' && $email != '' && $phone != ''){
$query = mysql_query("INSERT into Student(id, firstname, lastname, password, email, phone, course) values ('$id', '$fname', '$lname', '$password', '$email', '$phone', '$course')");
echo "Registered successfully!";
}
else{
echo "All fields must be filled!";
}
mysql_close( $db );
?>
I am still new to this and I am practicing. But I found out that the value I am trying to insert, is not added to my database. Why is it so? Did I do something wrong with codes in controller.js and the register.php? Can someone show me the mistakes I made and how can I correct it?
I would recommend you start by changing the $http.post to the following:
var body = {
'id':$scope.id,
'fname':$scope.fname,
'lname':$scope.lname,
'email':$scope.email,
'pass':$scope.pass,
'tel':$scope.tel,
'course':$scope.course
};
$http.post("http://localhost:81/fyp/register.php", body)
.then(function(response) {
console.log(response);
}, function(error) {
console.log(error);
}
The reason being that the .success method has been deprecated for this function, as described here:
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
This will probably not solve your problem, but the added error function should allow you to see whether there are any errors, which you can then share with us so we can help you further. The added variable for the body is completelyoptional.

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>

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