I am building a admin panel for a distribution company and they requested to have a page where they can add orders for all clients , so i generated a form which dynamically adds inputs for each product within the system and and for each client a row is created (see )
|The problem is , every product/client that is added, will add more and more inputs, i already had to increase max_input_vars, but this can easily reach to thousands , if not tens of thousands of inputs which will slow down the application dramatically , my question is, what is the best approach to process all these inputs, or another approach to achieve this functionality ?
I would either reconsider to add an maximum to the amount of input fields which are added per client or create a seperate page for each client on which the input fields are generated.
If you do want to continue you might want to consider extending the max_execution_time which defaults to 30 seconds, by adding ini_set('maximum_execution_time', '60'); to the top of your script.
To process all those rows on the server side. Make your input fields arrays which hold the client name as a key: <input type="text" name="your_value[client1][column1]" /> and for your next client do <input type="text" name="your_value[client2][column1]" /> increment the column for each column.
Then on the server side your can perform a foreach loop to get the values.
foreach($_POST[your_value] as $client)
{
foreach($client as $key => $val)
{
echo $val;
}
}
Use JavaScript (or something client side) to only submit the data that has changed.
If the chart is filled with stored data (in a DB I assume) than when an entry is changed you can use an AJAX request to your php script so it saves the changed data to the DB.
Related
As a follow-up to my last question, I have run into another problem. I am making a project on google homepage replica. The aim is to show search results the same as google and store the search history on a database. To show results, I have used this javascript:-
const q = document.getElementById('form_search');
const google = 'https://www.google.com/search?q=';
const site = '';
function google_search(event) {
event.preventDefault();
const url = google + site + '+' + q.value;
const win = window.open(url, '_self');
win.focus();
}
document.getElementById("s-btn").addEventListener("click", google_search)
To create my form, I have used the following HTML code:-
<form method="POST" name="form_search" action="form.php">
<input type="text" id="form_search" name="form_search" placeholder="Search Google or type URL">
The terms from the search bar are to be sent to a PHP file with the post method. I have 2 buttons. Let's name them button1 and button2. The javascript uses the id of button1 while button2 has no javascript and is simply a submit button.
The problem is that when I search using button1, the search results show up but no data is added to my database. But when I search using button2, no results show up( obviously because there is no js for it) but the search term is added to my database. If I reverse the id in javascript, the outcome is also reversed. I need help with making sure that when I search with button1, it shows results and also saves the data in the database. If you need additional code, I will provide it. Please keep your answers limited to javascript, PHP, or HTML solutions. I have no experience with Ajax and JQuery. Any help is appreciated.
Tony since there is limited code available so go with what you had stated in your question.
It is a design pattern issue not so much as so the event issue.
Copy pasting from Wikipedia "software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. Rather, it is a description or template for how to solve a problem that can be used in many different situations. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system."
So here is how things play out at present;
forms gets submitted to specific URL i.e. based on action attribute
Requested page gets Query sting in php and lets you play around with it
then from there on .....
3. either you get results from database and return response
4. or you put search request into database and return success response
Problem statement
if its 3 then search request is not added to database if its 4 then results in response to search request are not returned.
Solution
you need to combine both 3 and 4 in to one processing block and will always run regardless of the search query is.
So our design pattern could use mysql transaction so whole bunch of queries would run a single operation example
$db->beginTransaction(); // we tell tell mysql we will multiple queries as single operation
$db->query('insert query');
$results= $db->query('search query');
$db->commit(); // if we have reached to this end it means all went fine no error etc so we commit which will make database record insert query into database. If there were errors then mysql wont record data.
if($results) {echo $results;} else {echo 'opps no result found';}
slightly more safe version
try {
$db->beginTransaction(); // we tell tell mysql we will multiple queries as single operation
$db->query('insert query');
$results= $db->query('search query');
$db->commit(); // if we have reached to this end it means all went fine no error etc so we commit which will make database record insert query into database. If there were errors then mysql wont record data.
if($results) {echo $results;} else {echo 'opps no result found';}
} catch (\Throwable $e) {
// An exception has been thrown must rollback the transaction
$db->rollback();
echo 'oho server could not process request';
}
We have effectively combined two query operation into one always recording into database and always searching in database.
I have table user where id = primary key, lastchange = int with lastchange data (in seconds). And i have frontend page with js script. Also all users placed in div like table by pages. So, items has user id and used changed timevalue in attributes.
I want to request all changed user ids in 1 request (1 http and 1 sql). They can be changed by other user on site.
How can i do this? I dont want check every user in page by timer, there is too many requests.
In my mind it looks like:
js do get request with list of users in page in json format [{"id":1, "lastchange":123123},{"id":2, "lastchange":123123}...
Php does request in mysql like SELECT * FROM `users` WHERE `id` IN (1, 2, 3) AND `lastchange` NOT IN (123459, 123456, 123459); (this not works fine, there is no queue for lastchange, it checks all inside braces and result are wrong)
Php return only ids of different rows [1, 15, 22] etc. to js.
Js check every id separately in other request getting full info about user by id
I can check every user in php separately, but i want to know how can i do it with 1 SQL request
Sorry my bad English.
I think you might want to implement the solution differently as per the first comment.... but, if you want keep your current model the SQL you need would look something like:
SELECT * FROM users WHERE
(id = 1 AND lastchange <> 123123) OR
(id = 2 AND lastchange <> 123123) OR
...
This will keep the id's and the lastchange values that relate to each other being compared properly. It is pretty ugly SQL but not hard to generate in a loop.
Sorry my stupidness. I think i solve this.
Js request api with only user id in page
php response json like id, lastchange
js checking lastchange value and id in page
js request full data about changed user replaces old in page
Thx all for helping
I am continuing to work on my multi stage bootstrap form, and I have hit a roadblock trying to pull info from my DB.
The main page is PHP and is named quote_tool.php
I have the following functional requirements:
The data must come from the MySQL database.
The user should only receive data that they requested (i.e. a row from the db with info about user license should only be grabbed if the user checked a radio button to include user licenses on the form).
The information needs to be called from the DB without refreshing/reloading the page.
Currently I have a table in my DB with the following columns:
There are 3 different products in that table right now. The user can select a radio to say they want to include endpoints, and then there are 3 check boxes to allow the user to input a quantity for which endpoint(s) they want to include.
The input field looks like this:
<label for="device-9102" class="form-partner-label"><input type="checkbox" class="quote-chkbox" id="9102-chk"> 9102 IP Phone</label>
<input type="text" name="9102-quantity" class="form-endpoint-qty form-control" id="form-partner-9102" readonly value="0">
When the user checks the box and input a value this value is dynamically updated on the summary page as well in the following field:
<input type="text" readonly name="sum-9102-qty" class="summary-field sum-qty" id="sum-9102-qty">
There is also 2 other fields on the summary page regarding this product.
MSRP
Part Number
MSRP is a hidden field that will be used for additional calculations, but Part Number is visible on the summary page.
When the user inputs the value for the endpoint quantity I need to call the DB and pull the MSRP and Part Number from the refEndpoints table.
I am currently building a function to call the DB when the user hits the "Next" button on the form, and that looks like this:
//Call DB to fetch part number and msrp of 9102
$('#form-partner-9102').change(function()){
var quantity_9102 = $('#form-partner-9102').val();
if(quantity_9102 !== 0) {
}
});
This is the point that I am stuck at. I am not sure how to call the DB and place the values of the part number and the MSRP in the correct input fields on the summary page.
jQuery runs on the client side so it cannot connect to MySQL directly, however your question is tagged php, which runs on the server side and thus can connect to your database. First you will need to setup a PHP file that can respond to HTTP POST requests and return JSON. Here is a great answer that shows you how to do this: Returning JSON from PHP to JavaScript?
Once set up (and you will need to workout what parameters this PHP file takes in and how it converts this into a query so that it can respond) you can now setup some simple JavaScript to call this PHP file (lets call it query.php). Code that does this might look like this:
$.post('/query.php', {quantity: $('#form-partner-9102').val()}, function(resp) {
$('#PartNumber').html(resp.PartNumber);
});
Some important things to keep in mind are to always be sure to use prepared statements when taking user input and turning it into a query (don't just build a SELECT statement by joining strings). Also be sure to look at your event binding, you can probably write one generic handler for your inputs that takes the partner ID as a data-* attribute making your code smaller and easier to maintain.
When Duplicate is data checked and the confirmation box apears I want to insert data when I press the ok button.
When I press the cancel button data should not be insert in DB.
How can I do this? Here is what I did so far:
<?php
//insert data to database
$category=Null;
$model=Null;
$part=Null;
$remarks=Null;
$partcode=Null;
$partnumber=Null;
$user=$_SESSION['login_user'];
//Recive data from form
if(isset($_POST['category'])){$category = $_POST['category'];}
if(isset($_POST['model'])){$model = $_POST['model'];}
if(isset($_POST['part'])){$part= $_POST['part'];}
if(isset($_POST['remarks'])){$remarks = $_POST['remarks'];}
//Check Duplicate Data From DB
$check="Select * From part Where Category='$category' and Model='$model' and PartName='$part'";
$checkrun=mysqli_query($conn,$check);
$checkrow=mysqli_num_rows($checkrun);
if($checkrow>0){
echo "<script>confirm('Duplicate Data! Click OK to Add & Cancel to Edit')</script>";
}
//Make Part Number
$maxPartQry="Select max(PartCode) FROM part";
$maxPartRun=mysqli_query($conn,$maxPartQry);
$maxpart=mysqli_fetch_array($maxPartRun);
$partcode=$maxpart[0]+1;
$invID = str_pad($partcode,6,'0', STR_PAD_LEFT);
$partnumber=$model."-".$part."-".$invID;
$product;
//Insert Query For inserting data in DB
$sql = "INSERT INTO `part` (`ID`, `PartCode`, `PartNumber`, `Category`, `Model`, `PartName`, `Remarks`, `Date`, `Name`)
VALUES (NULL, '$partcode', '$partnumber', '$category', '$model', '$part','$remarks', NOW(), '$user');";
if(($category != Null) ){
$insert=mysqli_query($conn,$sql);
if($insert){
echo "<script>window.alert('New Part No. ".$partnumber." is Genrated Successfully!!')</script>";
}
}
?>
You need to understand that different pieces of code are executed at different locations. Eg:
SQL queries are executed on the server side
Alert / confirmation boxes are executed on the client side (web browser)
Code for what is executed on the client side is generated on the server side
So multiple requests towards the server are needed if you wish to implement a scenario such as:
User posts data to the server
Server responds that data are duplicates (and returns script code for user confirmation)
Confirmation code is executed, user accepts the insertion of a duplicate
Confirmation is sent towards the server or data are posted again with the addition of a "accept duplicate" flag (typically, if server is stateless).
Server receives the confirmation / second post request, identifies it should accept duplicates, and perform the corresponding SQL query for insertion.
Steps 1, 3, 4 happen on the client side. Steps 2, 5 happen on the server side
In the case the user cancels, then server side code just skips the second post request.
So, you need extra code on the server side to differentiate the two requests (Is this a confirmation request? or Should duplicates be allowed?), and adapt its behavior accordingly. And you need extra code on the client side to generate the second request if user confirms that a duplicate should be inserted.
Of course, all of this would be even cleaner if client-side code was static rather than generated at server-side (google REST HTTP interfaces, for instance) but I fear that explaining this would only confuse you at the present time.
I don't want my users to be able to change the ('+res.id+') and ('+res.level') using inspect element because if they do it changes the outcome of the submit button.
For example '+res.id+' is = 2 and 2 is equal to a firedragon, but if the person uses inspect element they can change that 2 to a 1 and 1 is equal to a lightningdragon. Then when they click battle the firedragon was changed to a lightningdragon. Basically they can battle whoever/whatever they want.
Is there anyway way to prevent people from changing those variables OR check if the variable was changed so I can send the user an error message?
html += '<form name="input" action="ingame.php?page=attack/travel/startbattle" enctype="multipart/form-data" method="post">';
html += '<input type="hidden" id="goid" name="goid" value="'+res.id+'">';
html += '<input type="hidden" id="level" name="level" value="'+res.level+'">';
html += ' <input type="submit" value="Battle!" class="button"/>';
html += '</form>';
If you want to store variables you can trust then don't send them to the client, instead keep them only in server memory (using Session state, a database, or some other backing-store that persists between requests).
If you need to share values with the client, then send them out but don't accept them as input from the user.
As a third option, if you have a completely stateless server and need to expose values to the client, then you can encrypt and/or sign the values, so that when they're returned from the client you can verify that they haven't been tampered with. Using Message Authentication Codes is one such implementation of this approach: http://en.wikipedia.org/wiki/Message_authentication_code
You can’t stop a user from submitting whatever parameters they like to your form endpoint. Even if you could somehow stop the form values from being changed, someone could use curl or the like to send a custom-crafted request to the server.
You need server-side validation of input values. You may need to store an intermediary object that can be retrieved when the form is submitted, then you won’t have to carry along those values as hidden fields.