avoiding duplicate mysql injection - php

I created a controller and called the function for one time.But it call two times and inserted the value two times.I call the service upload_album in controller.Now value got inserted for two times.one with original value and another with dummy value
Controller
$scope.savealbum = function() {
$scope.album_pids = $routeParams.id;
$timeout(function () {
//console.log($scope.justapp);
for (tt in $scope.justapp) {
if ($scope.justapp[tt].id == $scope.album_pids) {
for (var i = 0; i < $rootScope.media_lib.length; i++) {
}
}
}
$scope.promise=AlbumServices.upload_album($scope.album_pids,$scope.images,$scope.videos);
$scope.promise.then(function(data) {
console.log(data);
alert('Photos Added to Album Successfully');
// $location.path('album_details/' + $routeParams.id);
}, function(reason) {
console.log(reason);
});
}, 1500, false);
};
Service
upload_album: function (alb,img,vid) {
var deferred = $q.defer();
var data = {};
data.pagename = "upload_album";
data.album = alb;
data.photo = img;
data.video = vid;
$http.post('js/data/album.php', data)
.success(function (data, status, headers, config)
{
console.log(status + ' - ' + data);
deferred.resolve(data);
})
.error(function (data, status, headers, config)
{
deferred.reject(data);
console.log('error');
});
return deferred.promise;
}
php
function upload_album ($prefix) {
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$sub_id=$request->album;
$val=$request->photo;
$photo = json_encode($val);
$video = json_encode($request->video);
$now = date('Y-m-d H:i:s');
$count_pho = sizeof($photo);
$count_vid = sizeof($video);
$test = '';
if($count_pho != '0' ) {
$test .= "('".$sub_id."','".$content_type."','".$photo."','".$website_id."','".$now."'),";
$demo = substr($test, 0, -1);
$sql="INSERT INTO `album_details` (SUB_ID,CONTENT_TYPE,CONTENT_VALUE,WEBSITE_ID,CreatedTime)VALUES".$demo;
$query = mysql_query($sql) or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $sql, __LINE__);
}
if ($query) {
echo $msg = true;
} else {
echo $msg = false;
}
}

Because we cannot se the whole code (including the HTML) my suggestions are these:
check your html and/or run method inside angular to be sure that your controller was not instanciated twice
create a unique key pair in your database (it could help not have double records)
create a debouncer when using timeout so that if the timeout is always launched once. something like this:
var t = null;
var mySaveFunction = function () {
if (t) {
clearTimeout(t);
}
t = setTimeout(function () {
/* do saving here */
}, 2000);
};

Related

ionic v3 when make and update in the app to the data it is updating in the database but not in the app

I am new to ionic and I am trying to understand an app that has basic http query to communicate with the database, but I am facing a problem.
There is a page that show a list which has been taken from the database. There are two operations that can be performed on this list - insert and update. The problem occurres when I try to make an update. The record in the database is updated but not the list in the application is not. However, when I insert a new record the list got updated with the new record including all previous changes, that were not shown in the list.
Here is the type script for the list page:
export class CrudHttpListPage {
items: any;
constructor(public loading: LoadingProvider, private toast: ToastProvider, public modal: ModalController, private crud: CrudHttpProvider) { }
ionViewDidLoad() {
this.load();
}
load() {
this.loading.present();
this.crud.read.then(res => {
this.items = res;
if (res) this.loading.dismiss();
});
}
add() {
let modal = this.modal.create('CrudHttpDetailPage', { action: 1 });
modal.present();
modal.onDidDismiss(data => {
console.log(data);
if (data) this.load();
});
}
edit(item) {
let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
modal.present();
modal.onDidDismiss(data => {
if (data) this.load();
});
}
Here is the typescript code for the add and edit page:
export class CrudHttpDetailPage {
private form: FormGroup;
action: number;
data: any = { title: '', text: '' };
constructor(private view: ViewController, private toast: ToastProvider, private loading: LoadingProvider, private crud: CrudHttpProvider, private fb: FormBuilder, public params: NavParams) {
this.action = params.data.action;
this.data = params.data && params.data.data || this.data;
console.log(params.data);
this.form = this.fb.group({
id: [this.data && this.data.id],
title: [this.data && this.data.title, Validators.required],
text: [this.data && this.data.text, Validators.required]
});
}
submit() {
this.loading.present();
console.log(this.form.value);
this.crud.save(this.form.value).then(data => {
// this.dataNotes.id = data;
console.log(data);
this.loading.dismiss();
this.view.dismiss(this.form.value);
}, err => {
console.log(err);
this.loading.dismiss();
this.toast.showWithClose(err);
this.close();
});
}
close() {
this.view.dismiss();
}
}
Here are the http operations:
const SERVER_URL: any = {
getNormal: ConstantVariable.APIURL + 'index.php/tbl_note',
getLimit: ConstantVariable.APIURL + 'limit.php',
};
#Injectable()
export class CrudHttpProvider {
limitData: number = 10;
datas: any = [];
constructor(public http: Http) {
this.datas = null;
}
get read() {
return new Promise(resolve => {
this.http.get(SERVER_URL.getNormal).map(res => res.json()).subscribe(data => {
console.log(data.dataNotes);
resolve(data.dataNotes);
});
});
}
save(item) {
let headers: any = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }),
options: any = new RequestOptions({ headers: headers });
if (item.id) {
return new Promise((resolve, reject) => {
this.http.post(SERVER_URL.getNormal + '/' + item.id, item, options).map(res => res.json()).subscribe((data) => {
console.log(data);
resolve(data.dataNotes);
}, (err) => {
reject(err);
console.log("error: " + err);
});
});
}
else {
return new Promise(resolve => {
this.http.post(SERVER_URL.getNormal, item, options)
.map(res => res.json())
.subscribe(data => {
// console.log(data);
resolve(data.dataNotes[0].id);
}, error => {
console.log("error " + error);
});
});
}
}
and last here is the PHP file:
<?php
header('Access-Control-Allow-Origin: *');
require_once('config.php');
// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
// retrieve the table and key from the path
$table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$key = array_shift($request)+0;
// escape the columns and values from the input object
$columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
$values = array_map(function ($value) use ($link) {
if ($value===null) return null;
return mysqli_real_escape_string($link,(string)$value);
},array_values($input));
// build the SET part of the SQL command
$set = '';
for ($i=0;$i<count($columns);$i++) {
$set.=($i>0?',':'').'`'.$columns[$i].'`=';
$set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}
// create SQL based on HTTP method
if ($method == "POST" AND $key != "") { $method = 'PUT'; }
if ($method == "GET" AND $key != "") { $method = 'DELETE'; }
switch ($method) {
case 'GET':
$sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
case 'PUT':
$sql = "update `$table` set $set where id=$key"; break;
case 'POST':
$sql = "insert into `$table` set $set"; break;
case 'DELETE':
$sql = "delete from `$table` where id=$key"; break;
}
// excecute SQL statement
$result = mysqli_query($link,$sql);
// die if SQL statement failed
if (!$result) {
http_response_code(404);
die(mysqli_error());
}
// print results, insert id or affected row count
echo "{\"status\":\"ok\", \"dataNotes\":";
if ($method == 'GET') {
if (!$key) echo '[';
for ($i=0;$i<mysqli_num_rows($result);$i++) {
echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
}
if (!$key) echo ']';
} elseif ($method == 'POST') {
$set = '"id":"'.mysqli_insert_id($link).'"';
for ($i=1;$i<count($columns);$i++) {
$set.=($i>0?',':'').'"'.$columns[$i].'":';
$set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
}
echo "[{".$set."}]";
} elseif ($method == 'DELETE') {
echo '[{"id":"'.$key.'"}]';
} else {
echo mysqli_affected_rows($link);
}
echo "}";
// close mysql connection
mysqli_close($link);
The issue might be here:
edit(item) {
let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
modal.present();
modal.onDidDismiss(data => {
if (data) this.load(); // <---- seems this.load() is not executing
});
}
Seems this.load() is not executing after modal.onDidDismiss:
- check modal is dismissing
- check if data is not null/undefined
- check running this.load(), with no if() statement, does it run?
you may be able to find the answer there
edit(item) {
let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
modal.present();
modal.onDidDismiss(data => {
console.log('Modal has dismissed!!');
// if (data) this.load(); // comment for check
this.load();
});
}
i finally solved the problem. what cause the issue is that i have two files to make a connection to the database one for the website and the other is for the mobile application and it seems the one which i use in the mobile application is broken so i remove this file and connect to the old file and the problem solved

How to update MySQL database after view's value change

I got this sports website project written in Codeigniter/AngularJs and I'm stucked at the communication between view/controller/model.
There is this function that updates user points in view, then I should use this dataSavingHttp service to update the database also, but I'm really confused about its functionality
The View Angularjs controller
$scope.buy_salary_cap = function() {
$scope.remainSalary = parseInt($scope.contestDetails.salary_cap/10) + parseInt($scope.remainSalary);
$rootScope.profile_data.points_balance = parseInt($rootScope.profile_data.points_balance) + parseInt(1);
dataSavingHttp({
url: site_url+"lineup/update_user_points_balance",
data: {},
}).success(function (response) {
$scope.content = response.data.points_balance;
}).error(function (error) {
$scope.content = "Erro!";
});
$scope.isDisabled = true;
}
The Codeigniter controller
private function update_user_points_balance()
{
return $this->Lineup_model->update_user_points_balance();
}
The Model function
public function update_user_points_balance()
{
$condition = array('user_id' => $this->session->userdata('user_id'));
$config['points_balance'] = $this->remain_balance;
$this->table_name = USER;
return $this->update($condition , $config);
}
Here is the dataSavingHttp code
vfantasy.factory('dataSavingHttp', function($http, $location) {
var wrapper = function(requestConfig) {
var options = angular.extend({
url: "",
method: "POST",
data : '',
dataType: "json",
},requestConfig);
var httpPromise = $http(options);
httpPromise.success(function(result, status, headers, config){
var l = window.location;
wrapper.lastApiCallConfig = config;
wrapper.lastApiCallUri = l.protocol + '//' + l.host + '' + config.url + '?' +
(function(params){
var pairs = [];
angular.forEach(params, function(val, key){
pairs.push(encodeURIComponent(key)+'='+encodeURIComponent(val));
});
return pairs.join('&')
})(config.params);
wrapper.lastApiCallResult = result;
})
return httpPromise;
};
return wrapper;
});
Maybe there is a simpler solution, but I'm really new in these languages. Thanks in advance.

Ajax post requests in ServiceWorkers

Is it possible to make ajax post request in ServiceWorkers execution?
I have a Service Worker registered that just "listen" for a push notification.
I need to call a PHP function (in order to read some data from my database) during the execution of the Service Worker (when receiving the push notification), but I'm not able to do it. When I call the ajax post it goes to "error" section and the error is "No Transport" (I tried to add the "jQuery.support.cors = true;" like suggested in other thread, but this not fixed the issue).
Here below the serviceworker code.
Is it impossible to do what I'm trying to do, or I'm doing something wrong?
var document = self.document = {parentNode: null, nodeType: 9, toString: function() {return "FakeDocument"}};
var window = self.window = self;
var fakeElement = Object.create(document);
fakeElement.nodeType = 1;
fakeElement.toString=function() {return "FakeElement"};
fakeElement.parentNode = fakeElement.firstChild = fakeElement.lastChild = fakeElement;
fakeElement.ownerDocument = document;
document.head = document.body = fakeElement;
document.ownerDocument = document.documentElement = document;
document.getElementById = document.createElement = function() {return fakeElement;};
document.createDocumentFragment = function() {return this;};
document.getElementsByTagName = document.getElementsByClassName = function() {return [fakeElement];};
document.getAttribute = document.setAttribute = document.removeChild =
document.addEventListener = document.removeEventListener =
function() {return null;};
document.cloneNode = document.appendChild = function() {return this;};
document.appendChild = function(child) {return child;};
importScripts('js/jquery.js');
self.addEventListener('push', function(event) {
jQuery.support.cors = true;
var endpoint = "";
if (event.data) {
endpoint = event.data.text();
}
var data = {
query: "SELECT * FROM [TABLE] WHERE ENDPOINT = '" + endpoint + "'"
};
$.ajax({
data: data,
method: "POST",
url: 'ExecuteQueryJquery.php',
dataType: 'json',
success: function (obj, textstatus) {
var o = obj;
},
error: function (obj, textstatus) {
var o = obj;
}
});
});

Cart doesn't update after changing quantity

I am making a cart system using PHP and AJAX. Everything works pretty fine, except for the updating part. When the user clicks outside of the number form, the subtotal will update automatically. I used AJAX for this, but doesn't work. I tested this with the search, everything was fine.
AJAX function:
function initXML() { //Adaptation for old browsers
var _xmlhttp;
if (window.XMLHttpRequest) {
_xmlhttp = new XMLHttpRequest();
} else {
_xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return _xmlhttp;
}
function ajaxFormValidate(_config) {
/*Structure
type: 'GET' or 'POST',
url: 'request URL' Default: location.href,
method: true or false (optional). False for non-async, true for async,
sendItem: file or data to be sent,
success: a callback function when the request is complete
error: a fallback function when the request is failed
*/
if (!_config.type) {
_config.type = 'POST'; //Automatically set type to POST if no type property is declared
}
if (!_config.url) {
_config.url = location.href; //Automatically set url to self if no url property is declared
}
if (!_config.method) {
_config.method = true; //Automatically set method to true if no method property is declared
}
var _xmlHttp = initXML(); //Declare request variable
_xmlHttp.onreadystatechange = function(){
if (_xmlHttp.readyState === 4 && _xmlHttp.status === 200) {
if (_config.success) {
_config.success(_xmlHttp.responseText);
}
}
else {
if (_config.error) {
_config.error(_xmlHttp.responseText);
}
}
}; //Check readyState and status to handle the request properly
//Handle the items sent
var _Itemstring = [], _sendItem = _config.sendItem;
if (typeof _sendItem === "string") {
var _arrTmp = String.prototype.split.call(_sendItem, '&');
for (var i = 0; i < _arrTmp.length; i ++) {
var _tmpData = _arrTmp[i].split('=');
_Itemstring.push(encodeURIComponent(_tmpData[0]) + "=" + encodeURIComponent(_tmpData[1]));
}
}
else if (typeof _sendItem === "object" && !(_sendItem instanceof String || (FormData && _sendItem instanceof FormData))) {
for (var k in _sendItem) {
var _tmpData = _sendItem[k];
if (Object.prototype.toString.call(_tmpData) === "[object Array]") {
for (var j = 0; j < _tmpData.length; j ++) {
_Itemstring.push(encodeURIComponent(k) + '[]=' + encodeURIComponent(_tmpData[j]));
}
}
else {
_Itemstring.push(encodeURIComponent(k) + '=' + encodeURIComponent(_tmpData));
}
}
}
_Itemstring = _Itemstring.join('&');
if (_config.type === 'GET') {
_xmlHttp.open('GET', _config.url + "?" + _Itemstring, _config.method);
_xmlHttp.send();
}
else if (_config.type === 'POST') {
_xmlHttp.open('POST', _config.url, _config.method);
_xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
_xmlHttp.send(_Itemstring);
}
}
AJAX called inside a JS file handling the changes in the inputs
// JavaScript Document
window.addEventListener('load', function(){
var _ranum = document.getElementsByClassName('ranum');
for (var i = 0; i < _ranum.length; i ++) {
_ranum[i].addEventListener('blur', function(){ //Check click outside
var _this = this;
ajaxFormValidate({
type:'POST',
sendItem: {
u: _this.value, //Send the value after the change
id: _this.id, //Send the product id
},
success: function(response){
console.log('SUCCESS');
}
});
}, false);
}
}, false);
Handling the changes in PHP file
var_dump($_POST['u']);
if (isset($_POST['id'], $_POST['u'])) {
if (!empty($_POST['id']) && !empty($_POST['u'])) {
$id = mysqli_real_escape_string($conn, $_POST['id']);
$u = mysqli_real_escape_string($conn, $_POST['u']);
if (isset($_SESSION['cart'][$id])) {
$_SESSION['cart'][$id] = $u;
}
}
}
I see the it logged out 'SUCCESS' in the console, however, when I use var_dump($_POST['u']) it doesn't work. Also, it updates the subtotal only if I reload the page.
What did I do wrong? I pretty sure my AJAX function is correct, and JS logged out 'SUCCESS', so what's the problem? Thanks very much

Display name one by one using JSON and AJAX

How to display name one by one using ajax. It seem that my FOR looping is not working to push name one by one. Is there any step that i miss? Can someone point me to where/what i did wrong.
var names = [];
var profiles = {};
var restURL = "fetch.php";
function refresh() {
$.ajax({
method: 'GET',
url:restURL,
success: function (result, status, xhr) {
for (var k in result) {
var name = result[k].name;
if (!profiles.hasOwnProperty(name)) {
names.push(name);
profiles[name] = result[k];
}
}
}
});
}
var namei = -1;
function nextName() {
namei++;
if (namei > names.length - 1) {
namei = Math.max(1, names.length - 10) - 1;
}
console.log(namei + '/' + names.length);
$('.texts li:first', '.jumbotron #atname').text(profiles[names[namei]].name);
$('.texts li:first', '.jumbotron #atdiv').text(profiles[names[namei]].division);
$('.jumbotron .tlt').textillate('start');
setTimeout(function () {
$('.jumbotron .tlt').textillate('out');
}, 5000);
}
fecth.php
$i=1;
while ( $row = mysql_fetch_assoc($rs) ) {
$response['result'][] = array(
'staffno' => $row['g_idm'],
'name' => $row['g_name'],
'division' => $row['g_div']
);
$i++;
}
echo json_encode($response);

Categories