Ajax not working properly. PHP cannot insert data in SQL - php

I am using Jquery array to fetch variables on dynamic input forms. I could group and output the arrays into the console.log, but no data could be inserted within the multiple table database itself.
here's the Jquery code with ajax and console.log
$("button[name='submit_addPackresCategories']").click(function(){
var packres_categories_name;
$("input[id='packres_categories_name']").each(function(){
packres_categories_name = this.value;
});
console.log(packres_categories_name);
var packres_categories_description;
$("textarea[id='packres_categories_description']").each(function(){
packres_categories_description = this.value;
});
console.log(packres_categories_description);
var packres_categories_paxhead_day = {};
$("input[id^='packres_categories_paxhead_day']").each(function(){
packres_categories_paxhead_day[this.id] = this.value;
});
console.log(packres_categories_paxhead_day);
var packres_categories_paxhead_price = {};
$("input[id^='packres_categories_paxhead_price']").each(function(){
packres_categories_paxhead_price[this.id] = this.value;
});
console.log(packres_categories_paxhead_price);
var packres_categories_paxgroup_size = {};
$("input[id^='packres_categories_paxgroup_size']").each(function(){
packres_categories_paxgroup_size[this.id] = this.value;
});
console.log(packres_categories_paxgroup_size);
var packres_categories_paxgroup_consumable = {};
$("input[id^='packres_categories_paxgroup_consumable']").each(function(){
packres_categories_paxgroup_consumable[this.id] = this.value;
});
console.log(packres_categories_paxgroup_consumable);
$.ajax({
url: "ajax/addPackresCategories.php",
type: "post",
data: {
packres_categories_name: packres_categories_name,
packres_categories_description: packres_categories_description,
packres_categories_paxhead_day: packres_categories_paxhead_day,
packres_categories_paxhead_price: packres_categories_paxhead_price,
packres_categories_paxgroup_size: packres_categories_paxgroup_size,
packres_categories_paxgroup_consumable: packres_categories_paxgroup_consumable
}
})
.done(function(response){
if (JSON.parse(response)) {
alert("Successfully Added New Package!");
}
else {
alert("Failed!");
}
});
});
here's the url for the ajax
<?php
include_once("../db.php");
include "admin_session.php";
$packres_categories_name = $_POST["packres_categories_name"];
$packres_categories_description = $_POST["packres_categories_description"];
$packres_categories_paxhead = array_combine($_POST["packres_categories_paxhead_day"], $_POST["packres_categories_paxhead_price"]);
$packres_categories_paxgroup = array_combine($_POST["packres_categories_paxgroup_size"], $_POST["packres_categories_paxgroup_consumable"])
$sql_insertPackresNameDesc_packresCategories = "INSERT INTO packres_categories(packres_categories_name, packres_categories_description) VALUES('" . mysqli_real_escape_string($conn, $packres_categories_name) . "', '" . mysqli_real_escape_string($conn, $packres_categories_description) . "')";
$query_sql_insertPackresNameDesc_packresCategories = $conn->query($sql_insertPackresNameDesc_packresCategories);
$affectedRows_query_sql_insertPackresNameDesc_packresCategories = mysqli_affected_rows($conn); //will be used to verify if inserted properly on database later
$packres_id = mysqli_insert_id($conn);//will be used later
foreach ($packres_categories_paxhead as $key => $value) {
$sql_insertPackresCategoriesPaxhead_packresCategoriesPaxHead = "INSERT INTO packres_categories_paxhead(packres_id, packres_categories_paxhead_day, packres_categories_paxhead_day) VALUES('" . mysqli_real_escape_string($conn, $packres_id) . "', '" . mysqli_real_escape_string($conn, $key) . "', '" . mysqli_real_escape_string($conn, $value) . "')";
$query_sql_insertPackresCategoriesPaxhead_packresCategoriesPaxHead = $conn->query($insertPackresCategoriesPaxhead_packresCategoriesPaxHead);
$affectedRows_query_sql_insertPackresCategoriesPaxhead_packresCategoriesPaxHead += mysqli_affected_rows($conn);
}
foreach ($packres_categories_paxgroup as $key => $value) {
$sql_insertPackresCategoriesPaxGroup_packresCategoriesPaxgroup = "INSERT INTO packres_categories_paxgroup(packres_id, packres_categories_paxgroup_size, packres_categories_paxgroup_consumable) VALUES('" . mysqli_real_escape_string($conn, $packres_id) . "', '" . mysqli_real_escape_string($conn, $key) . "', '" . mysqli_real_escape_string($conn, $value) . "')";
$query_sql_insertPackresCategoriesPaxGroup_packresCategoriesPaxgroup = $conn->query($sql_insertPackresCategoriesPaxGroup_packresCategoriesPaxgroup);
$affectedRows_query_sql_insertPackresCategoriesPaxGroup_packresCategoriesPaxgroup += mysqli_affected_rows($conn);
}
$conn->close();
if (($affectedRows_query_sql_insertPackresNameDesc_packresCategories != 0) && ($affectedRows_query_sql_insertPackresCategoriesPaxhead_packresCategoriesPaxHead != 0) && ($$affectedRows_query_sql_insertPackresCategoriesPaxGroup_packresCategoriesPaxgroup != 0)) {
echo json_encode(true);
}
else {
echo json_encode(false);
}
?>
arrays of data should be inserted properly into the database, but no data were entering the database.
error line being thrown at console
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.<anonymous> (master.js:70)
at u (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at k (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)

json_encode()- returns the JSON representation of a value.
And you are returning boolean

Related

php ajax mysql update using for loop taking more time to execute what's good practice?

here i need update more than 100s of data at time. this query works for me but its too slow at least it take 15 to 20 seconds to execute.
i have tried few things but failed
any help appreciated. iam still learner .
<?php
include "../connection.php";
if (isset($_POST['close_val'])) {
$item_cid = $_POST["item_cid"];
$item_id = $_POST["item_id"];
$op_date = $_POST["op_date"];
$op_value = $_POST["op_value"];
$close_date = $_POST["close_date"];
$close_val = $_POST["close_val"];
$PurchaseRate = $_POST["PurchaseRate"];
$GeneralRate = $_POST["GeneralRate"];
$WholeSaleRate = $_POST["WholeSaleRate"];
$WholeSaleQty = $_POST["WholeSaleQty"];
for ($count = 0; $count < count($item_id); $count++) {
$item_cid_clean = mysqli_real_escape_string($conn, $item_cid[$count]);
$item_id_clean = mysqli_real_escape_string($conn, $item_id[$count]);
$op_date_clean = mysqli_real_escape_string($conn, $op_date[$count]);
$op_value_clean = mysqli_real_escape_string($conn, $op_value[$count]);
$close_date_clean = mysqli_real_escape_string($conn, $close_date[$count]);
$close_val_clean = mysqli_real_escape_string($conn, $close_val[$count]);
$PurchaseRate_clean = mysqli_real_escape_string($conn, $PurchaseRate[$count]);
$GeneralRate_clean = mysqli_real_escape_string($conn, $GeneralRate[$count]);
$WholeSaleRate__clean = mysqli_real_escape_string($conn, $WholeSaleRate[$count]);
$WholeSaleQty_clean = mysqli_real_escape_string($conn, $WholeSaleQty[$count]);
$updatequery = "UPDATE table1 SET
`item_cid` = '" . $item_cid_clean . "',
`item_id` = '" . $item_id_clean . "',
`op_date` = '" . $op_date_clean . "',
`op_value` = '" . $op_value_clean . "',
`close_date` = '" . $close_date_clean . "',
`close_val` = '" . $close_val_clean . "',
`PurchaseRate` = '" . $PurchaseRate_clean . "',
`GeneralRate` = '" . $GeneralRate_clean . "',
`WholeSaleRate` = '" . $WholeSaleRate__clean . "',
`WholeSaleQty` = '" . $WholeSaleQty_clean . "'
WHERE close_date='" . $close_date_clean . "'
and `item_id` = '" . $item_id_clean . "' ";
mysqli_query($conn, $updatequery);
}
$return_arr = array('item_cid' => $item_cid, 'item_id' => $item_id, 'op_date' => $op_date, 'bar' => $item_type);
echo json_encode($return_arr);
}
?>
this ajax used to initialize Array to post to php
var item_cid = [];
var item_id = [];
var op_date = [];
var op_value = [];
var close_date = [];
var close_val = [];
var PurchaseRate = [];
var GeneralRate = [];
var WholeSaleRate = [];
var WholeSaleQty = [];
// Initializing array with Checkbox checked values
$("input[name='item_cid[]']").each(function() {
item_cid.push(this.value);
});
$("input[name='item_id[]']").each(function() {
item_id.push(this.value);
});
$("input[name='op_date[]']").each(function() {
op_date.push(this.value);
});
$("input[name='op_value[]']").each(function() {
op_value.push(this.value);
});
$("input[name='close_date[]']").each(function() {
close_date.push(this.value);
});
$("input[name='close_val[]']").each(function() {
close_val.push(this.value);
});
$("input[name='PurchaseRate[]']").each(function() {
PurchaseRate.push(this.value);
});
$("input[name='GeneralRate[]']").each(function() {
GeneralRate.push(this.value);
});
$("input[name='WholeSaleRate[]']").each(function() {
WholeSaleRate.push(this.value);
});
$("input[name='WholeSaleQty[]']").each(function() {
WholeSaleQty.push(this.value);
});
$.ajax({
url: myurl,
type: 'post',
data: {
item_cid: item_cid,
item_id: item_id,
op_date: op_date,
op_value: op_value,
close_date: close_date,
close_val: close_val,
PurchaseRate: PurchaseRate,
GeneralRate: GeneralRate,
WholeSaleRate: WholeSaleRate,
WholeSaleQty: WholeSaleQty
},
dataType: 'JSON',
success: function(response) {
//success
}
here php ajax html code every step checks out correct its working only php part of mysql query in loops needs fix.
If you prepare the query outside your loop you will compile the query only once. If you use mysqli_query() inside the loop you have to compile the query once per update, thats a overhead you can do without as it is a complete waste of time.
So write the query as a prepared parameterised query as below so you compile it once and then use it to execute the update multiple times. This wont make a magical improvement, but it shoudl be the way you always do your database quertying as it also preotects your database from SQL Injection Attack
$sql = "UPDATE table1
SET `item_cid` = ?, `item_id` = ?, `op_date` = ?
`op_value` = ?, `close_date` = ?, `close_val` = ?,
`PurchaseRate` = ?, `GeneralRate` = ?,
`WholeSaleRate` = ?, `WholeSaleQty` = ?
WHERE close_date=? and `item_id` = ?";
$stmt = $conn->prepare($sql);
foreach( $_POST["item_id"] as $idx => $itemid ) {
// you may have to check the data types used in here
// however mysqli does not normally care about that as much as you might hope
$stmt->bind_param('ssssssssssss',
$_POST["item_cid"][$idx],
$itemid,
$_POST["op_date"][$idx],
$_POST["op_value"][$idx],
$_POST["close_date"][$idx],
$_POST["close_val"][$idx],
$_POST["PurchaseRate"][$idx],
$_POST["GeneralRate"][$idx],
$_POST["WholeSaleRate"][$idx],
$_POST["WholeSaleQty"][$idx],
$_POST["close_date"][$idx],
$_POST["item_id"][$idx]
);
$stmt->execute();
}
// not sure what you are trying to do here
// as these are arrays and you do this after the loop
$return_arr = array('item_cid' => $item_cid, 'item_id' => $item_id, 'op_date' => $op_date, 'bar' => $item_type);
echo json_encode($return_arr);
}
If you don't already have this, it should help with speed:
INDEX(item_id, close_date)
For further discussion please provide
SHOW CREATE TABLE
A sample query after it is constructed. Two samples, if that generates lots of separate UPDATEs. Be sure to have different values for item_id and close date unless one of them does not change.
(You can leave out most of the columns.)
I may be able to show you how to do all the Updates in a single IODKU. (But currently the requirements are vague.)

how to insert multiple rows inside database using PHP MySQL ajax using better technique for faster insert

here i'am trying to insert multiple rows at same time in my case more than 200-250 rows at same time but i got below error
Unknown: Input variables exceeded 1000. To increase the limit change max_input_vars in php.ini
but when i increased the max_input_vars = 3000 this solved problem was now iam able to insert but it is taking too much time.
i want to insert faster but need help
this is my php code
<?php
include "connection.php";
if (isset($_POST['close_val'])) {
$item_cid = $_POST["item_cid"];
$item_id = $_POST["item_id"];
$op_date = $_POST["op_date"];
$op_value = $_POST["op_value"];
$close_date = $_POST["close_date"];
$close_val = $_POST["close_val"];
// Converting the array to comma separated string
for ($count = 0; $count < count($item_id); $count++) {
$item_cid_clean = mysqli_real_escape_string($conn, $item_cid[$count]);
$item_id_clean = mysqli_real_escape_string($conn, $item_id[$count]);
$op_date_clean = mysqli_real_escape_string($conn, $op_date[$count]);
$op_value_clean = mysqli_real_escape_string($conn, $op_value[$count]);
$close_date_clean = mysqli_real_escape_string($conn, $close_date[$count]);
$close_val_clean = mysqli_real_escape_string($conn, $close_val[$count]);
$sql = "SELECT COUNT(*) AS cntuser from bar_opening_details WHERE `item_id` = '" . $item_id_clean . "' AND close_date='" . $close_date_clean . "' AND item_cid='" . $item_cid_clean . "' ";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$count1 = $row['cntuser'];
if ($count1 > 0) {
// update
$updatequery = "UPDATE bar_opening_details SET
`item_cid` = '" . $item_cid_clean . "',
`item_id` = '" . $item_id_clean . "',
`op_date` = '" . $op_date_clean . "',
`op_value` = '" . $op_value_clean . "',
`close_date` = '" . $close_date_clean . "',
`close_val` = '" . $close_val_clean . "'
WHERE close_date='" . $close_date_clean . "' and `item_id` = '" . $item_id_clean . "' ";
mysqli_query($conn, $updatequery);
} else {
$insertquery = "INSERT INTO bar_opening_details
(item_cid,
item_id,
op_date,
op_value,
close_date,
close_val) values ('" . $item_cid_clean . "', '" . $item_id_clean . "', '" . $op_date_clean . "', '" . $op_value_clean . "', '" . $close_date_clean . "', '" . $close_val_clean . "')";
mysqli_query($conn, $insertquery);
}
}
// insert
$return_arr = array('item_cid' => $item_cid, 'item_id' => $item_id, 'op_date' => $op_date, "close_val" => $count);
echo json_encode($return_arr);
mysqli_close($conn);
}
here is my ajax code. using this iam able to sent request to insert but it is takin to much time
<script>
$(document).ready(function() {
// submit button click
$("#submit").click(function() {
$('#loading').show();
var item_cid = [];
var item_id = [];
var op_date = [];
var op_value = [];
var close_date = [];
var close_val = [];
var Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
});
// Initializing array with Checkbox checked values
$("input[name='item_cid[]']").each(function() {
item_cid.push(this.value);
});
$("input[name='item_id[]']").each(function() {
item_id.push(this.value);
});
$("input[name='op_date[]']").each(function() {
op_date.push(this.value);
});
$("input[name='op_value[]']").each(function() {
op_value.push(this.value);
});
$("input[name='close_date[]']").each(function() {
close_date.push(this.value);
});
$("input[name='close_val[]']").each(function() {
close_val.push(this.value);
});
$.ajax({
url: 'lib/cbentry.php',
type: 'post',
data: {
item_cid: item_cid,
item_id: item_id,
op_date: op_date,
op_value: op_value,
close_date: close_date,
close_val: close_val
dataType: 'JSON',
success: function(response) {
$('.details').show();
// selecting values from response Object
var name = response.close_val;
$('#loading').hide();
// var email = response.email;
// var lang = response.lang;
// var foundjquery = response.foundjquery;
Toast.fire({
icon: 'success',
title: 'Data Entered Successfully'
})
// setting values
$('#name').text(name);
// $('#email').text(email);
// $('#lang').text(lang);
// $('#foundjquery').text(foundjquery);
}
});
});
});
</script>
JSON
A simple 2-line fix to allow for unlimited items: Suggest you encode the array into JSON for POSTing, then use json_decode() to turn it back into an array when it arrives in PHP.
But, I have to ask... Are there really hundreds of new (or changed) rows? If only a few rows, consider shipping one row at a time via AJAX to PHP -- perhaps based on whether a value has changed after the mouse leaves "focus". A lot of little AJAX calls would have a lot of overhead (launching many PHP threads), but the task would be finished by the time you leave the web page. It would "feel" as if every thing was "instantaneous". (OK, if you have a thousand users doing this same thing at the same time, this technique could overload the server.)
Arrays
Here's another approach: Use "arrays". If the input names end in []:
<input type=text name=x[] ">
the will come in as an array in $x. If you have multiple of these, then the subscripts (0, 1, ...) will let you match them up.
$list = GetArray('list');
function GetArray($fn) {
// Input an array of things from
// echo "<input type=checkbox name=\"fn[]\" value=\"$out_fn\" $checked>\n";
// url has &fn[]=aaa&fn[]=ccc
$req = #$_REQUEST[$fn]; // Note: this must NOT end in []
$fns = empty($req) ? [] :
(is_array($req) ? $req :
explode(',', $req));
return $fns; // always an array
}
($_REQUEST includes $_POST; change it if you would prefer)
INSERT
As for the speed of a MySQL insert... A single INSERT with 100 rows will run 10 times as fast 100 1-line INSERTs. So, if there are really hundreds of new rows, I recommend "batching" the inserts.
If most of the rows are already in the table, then INSERT IGNORE is a 'simple' way to deal with that. But... If there is an AUTO_INCREMENT id on the table, the dups will "burn" ids.
IODKU is the optimal way to deal with rows that are either new or modified. It, too, can be batched. But, it also burns ids if the query is not including the original id where available.
(I can elaborate, you you elaborate.)

AJAX and PHP code not working

I am sending my form data through AJAX but for some reason my PHP script is not running. The test echo's Im using in my PHP script is not showing. The window.alert("success") does show but HIDE and SHOW form1 and form2 also does not work.
Here is the code:
$('#mainform').on('submit', function(event) {
//test for empty fields
//test for Bots
//insert data into DB
//pass t_code on to next form
//create a page number for tabs
event.preventDefault(); //stops form on submit
var a = document.forms["mainform"]["hidden"].value;
if (a === ""){
var formData = {};
$.each($("#mainform").serializeArray(), function (i, field) {
formData[field.name] = field.value;
});
$.ajax({
url: 'insert_tut_description.php',
data: formData,
method:'POST',
success: function(response) {
window.alert("success");
pnum = 1;
t_code = form.elements["t_code"].value;
$("#form1").hide();
$("#form2").show();
document.getElementById("pnum").innerHTML = pnum;
}
});
};
});
<?php
echo "php running";
require 'config/config.php';
$t_title = $conn->real_escape_string($_POST['t_title']);
$t_code = $conn->real_escape_string($_POST['t_code']);
$t_image = $conn->real_escape_string($_POST['t_image']);
$hidden = $conn->real_escape_string($_POST['hidden']);
$t_desc = $conn->real_escape_string($_POST['t_desc']);
$t_url = "something.php";
echo $t_title;
echo t_url;
if(empty($hidden)){
echo "hidden is empty";
$query = "INSERT into tutorial_list (title, description, t_code, t_url, image,) VALUES('" . $t_title . "','" . $t_desc . "','" . $t_code . "','" . $t_url . "','" . $t_image . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
} else {
$conn->close();
}
}
?>

Change variable in external php file using ajax

i've encountered a problem changing php variable that is respobsible for showing content
here's my JS code:
$(document).ready(function(){
var ajax = 1;
var button;
$('.tagbtn').click(function(){
button = $(this);
$(this).siblings("ul").slideToggle('slow', function(){
$('.selection').click(function(){
var number = $(this).children('h1').html();
button.html(number);
$(this).parent('ul').slideUp('slow');
var data = 'number=' + number;
$.ajax({
type:'POST',
//url: 'ajax-realizacje.html',
url: 'aktualnosci.class.php',
async: true,
data: data,
success: function(){
limit_page = number;
}
});
});
});
});
});
limit_page is the variable from the external file, which i am trying to change
and here's my php function that loads the content:
function LoadArticles($pages = 0, $page = 0) {
$start = ($pages - $page) * $this->limit_page;
$q = "SELECT p.*, d.title, d.title_url, d.content, d.content_short, d.tagi FROM " . $this->table . " p ";
$q .= "LEFT JOIN " . $this->tableDescription . " d ON p.id=d.parent_id ";
$q .= "WHERE d.language_id=? AND p.active=1 AND d.active=1 ";
$q .= "ORDER BY p.date_add DESC, p.id DESC ";
$q .= "LIMIT ?,? ";
$params = array(
array(dbStatement::INTEGER, _ID),
array(dbStatement::INTEGER, $start),
array(dbStatement::INTEGER, $this->limit_page)
);
$statement = $this->db->query($q, $params);
$articles = array();
while ($row = $statement->fetch_assoc()) {
$row['content'] = strip_tags($row['content']);
$row['url'] = BASE_URL . '/' . $this->modul . '/' . $row['title_url'] . '.html';
$row['photo'] = $this->getPhotoUrl($row['photo']);
$row['date_add_org'] = $row['date_add'];
if (!empty($row['tagi'])) {
$row['tagi_url'] = explode('|', str_replace(' ', '-', $row['tagi']));
$row['tagi'] = explode('|', $row['tagi']);
}
$row['date_add'] = date("j", strtotime($row['date_add_org'])) . " " . miesiac2(date("n", strtotime($row['date_add_org']))) . " " . date("Y", strtotime($row['date_add_org'])) . "r";
$articles[] = $row;
}
return $articles;
}
the problem is that ajax doesn't seem to change that php variable
would appreciate your help
if it's just a text on a file you can read it by using:
$this->limit_page = file_get_contents('path/to/file');

Jquery security regarding mysql injection

I know its probably unconventional but I want to know if the below code is secure or not.
First piece of code is htee jquery object creation plus the call to the retrieve_data function:
var dataset = [
{
query_column: "articles.id,articles.category_id,articles.text,articles.slug article_slug,site_categories.title,site_categories.slug site_categories_slug",
table_name: 'articles',
query_join: 'LEFT JOIN site_categories ON site_categories.Id = ' + category,
query_filter: ['articles.category_id LIKE ', '%' + category + '%'],
query_limit: 'LIMIT ' + limit,
unique_column_switch: '1'
}
];
retrieve_data(dataset, function (data) {
Next is the retrieve_data function itself:
function retrieve_data(dataset, callback) {
$.ajax(
{
type: "POST",
url: "<?php echo ROOT_URL; ?>php/content/retrieve_data.php",
data: {json: JSON.stringify(dataset)},
success: function (data) {
var data = $.parseJSON(data);
callback(data);
}
});
}
Finally the php that retrieves the data and prints it out for the return to jquery:
mb_internal_encoding("UTF-8");
session_start();
include '../../config.php';
include ROOT_DIR . "php/dbconnection/dbconnection.php";
include ROOT_DIR . 'php/authentication/encryption.php';
$encrypt_decrypt = new encryption();
$json = json_decode($_POST['json']);
$array = array();
/*
* THIS IS TO BUILD A STRING OF DIFFERENT QUERIES TO BE PERFORMED UPON UPDATE BEING PRESSED
* PARAMS:
* data_value:::::::::::: THE VALUE USED TO FIND THE ROW
* table_name:::::::::::: TABLE NAME
* unique_column::::::::: UNIQUE DATA ELEMENT THAT LINKS ALL THE TABLES TOGETHER
* query_end::::::::::::: END OF QUERY (EXTRA WHERE CLAUSES, ORDER BY, LIMIT, ETC)
* query_column:::::::::: COLUMNS THAT ARE GOING TO BE CALLED, DEFAULTS TO * IF USING JOINS THEN THIS MUST BE SPECIFIED I.E. TABLE1.*, TABLE2.*, ETC
* query_join:::::::::::: SET ANY JOINS HERE
* unique_column_switch:: IF SET TO 1 DISABLES USE OF A UNIQUE COLUMN AND USES QUERY END EXCLUSIVELY
*/
foreach($json as $item){
$table_name = $mysqli->real_escape_string($item->table_name);
$unique_column = $mysqli->real_escape_string($item->unique_column);
$data_value = $mysqli->real_escape_string($item->data_value);
$query_column = $mysqli->real_escape_string($item->query_column);
$query_join = $mysqli->real_escape_string($item->query_join);
$query_filter = $item->query_filter;
$query_order = $mysqli->real_escape_string($item->query_order);
$query_limit = $mysqli->real_escape_string($item->query_limit);
$unique_column_switch = $mysqli->real_escape_string($item->unique_column_switch);
$query_filter_safe = array();
foreach($query_filter as $key1 => $val1){
array_push($query_filter_safe, ($key1 % 2) ? "'" . $mysqli->real_escape_string($val1) . "'" : $mysqli->real_escape_string($val1));
}
if(empty($unique_column) && $unique_column_switch != '1'){
$query1 = $mysqli->query("SHOW KEYS FROM `$table_name` WHERE Key_name = 'PRIMARY'");
$fetch1 = $query1->fetch_array(MYSQLI_ASSOC);
$unique_set = $fetch1['Column_name'] . " = '" . $data_value . "'";
$unique_column = $fetch1['Column_name'];
} else{
$unique_set = ($unique_column_switch != '1') ? "`" . $table_name . "`.`" . $unique_column . "` = '" . $data_value . "'" : '';
}
$unique_column = (empty($unique_column)) ? '' : $unique_column;
$where = (empty($unique_set) && empty($query_filter)) ? '' : 'WHERE';
$select_items = (empty($query_column)) ? '*' : $query_column;
$query2 = "SELECT " . $select_items . " FROM " . $table_name . " " . $query_join . " " . $where . " " . $unique_set . " " . join(' ', $query_filter_safe) . " " . $query_order . " " . $query_limit;
//echo $query2;
$query2 = $mysqli->query($query2);
for($x = 0; $fetch2 = $query2->fetch_array(MYSQLI_ASSOC); $x++){
$fetch2 = $encrypt_decrypt->decrypt_val($fetch2, $table_name, $mysqli);
foreach($fetch2 as $column => $value){
($unique_column == $column) ? $array[$table_name][$x]['INDEX_VALUE'] = $value : $array[$table_name][$x][$column] = $value;
}
}
}
echo json_encode($array);
EDIT 12/5 12:00PM EST
I have rewritten what I was trying to do. Thanks again for pointers everyone! #MonkeyZeus and #Carth were extremely useful.
include '../../config.php';
include ROOT_DIR . "php/dbconnection/dbconnection_pdo.php";
$query = "SELECT * FROM site_users WHERE username = :username";
$query = $pdo->prepare($query);
$query->execute(array('username' => $_POST['username']));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
Going back to jquery:
function article_box_basic(category, limit, max_char_count, location) {
$.ajax(
{
type: "POST",
url: "<?php echo ROOT_URL; ?>php/content/article_box_basic.php",
data: {username: 'moltmans'},
success: function (data) {
var data = $.parseJSON(data);
Do something here with data
This is emphatically not a "secure" approach. Validation and control on the client side should be treated as an inherently insecure convenience for generating a request not a means of enforcing true security. Your server side code should be validating the request parameters within the context of who your user is and what they're doing. Since a user can set "dataset" to whatever they want it doesn't matter if the category variable is itself prone to injection based on its usage in the rest of the statement.
By exposing your schema on the client side like this you're revealing valuable information that there's no need to expose.

Categories