php comparing value from database with one in a textbox - php

i have a multiple amount of text fields, the amount of text fields is due to how much data is in a database. The input for both are integers, all i want is when the values are inputted into the text fields it throws an error if the inputted data is larger than the value in the data base
for example
in a markscheme
the data inputted into the textbox is the mark given to the student and the data in the database is the maxmark for that particular question, so therefore it cannot exceed that value
so in effect i want to compare the values and if the text input value is larger than that of the one in the database it throws and error :)

If it's OK for you to rely on your users having javascript enabled, I would say the easiest is to verify the data on the client side.
You could do something like this:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<input type="text" value="5" name="grade[123]" data-max="10" />
<script type="text/javascript">
$(function() {
$('input[type="text"]').blur(function(e) {
var $this = $(this);
var max = parseInt($this.data('max'), 10);
if (parseInt($this.val(), 10) > max) {
var name = $this.attr('name');
console.error('Value ' + $this.val() + ' in field "' + name + '" exceed its maximum value of ' + max);
$this.focus();
}
})
});
</script>
</body>
</html>
Or you could replace all this logic with simple HTML5 number fields:
<input type="number" value="5" name="grade[123]" min="0" max="10" />
Obviously, one should never trust their users. You should always double-check the data on the server side and notify users about the possible errors.
This is something you could do:
<?php
if (!empty($_POST)) {
// ...
// fetch max values from the database in the form of
// array(
// id => [max],
// );
$maxValues = array( /* ... */ );
// prepare some error array if you want to show errors next to individual fields
$errors = array();
// ...and then loop through the posted array
foreach ($_POST['grades'] as $id => $value) {
// make sure the submitted value is an integer
if (!ctype_digit($value) && !is_int($value)) {
$errors[$id] = 'Invalid value';
continue;
}
if ((int) $value > (int) $maxValues[$id]) {
$errors[$id] = 'Value cannot be more than ' . $maxValues[$id];
}
}
// assign errors to the view or do whatever is required in your script
// ...
}
It shouldn't be difficult to understand what I was doing there. Basically, have one reference array and the data array to verify against (note: your HMTL field names must have the square brackets in them to act as arrays). And then just loop through the submitted data and verify against the reference array.
Just like Ryan Kempt said, there are lots of ways you could do it and without a specific example of your data structure or how you want the errors/exceptions to be presented to the user, it's quite difficult to write you an exact code.
Nevertheless, have a look at our suggestions and start from there. And best of luck!

Lots of ways to tackle this but pretty much with everything you can use a javascript solution for client-side checking and PHP for server-side... for front-end you could query the DB and output the information in hidden inputs and then compare the value of the textbox to the value of the matching hidden div using a javascript solution.
When the textbox loses focus you could use AJAX and query what's in the textbox against your database.
When the user submits the form finally you should also then verify the numbers again against the daabase using PHP.
So... would need more information but the above steps are what you're going to want to do - how you do them is up to you and if you need specific help after trying the above methods and running into issues, we'd love to help you more.
Happy coding and best of luck!

Related

Multiple Variables Explode and Insert to MySQL

I checked for a possible solution in the site and found no solution. I have a form which has two text fields for the user to enter Name and Mobile Number. By default the page shows only two fields. If the user wants he can add more. The problem is, I am unable to insert these multiple data into DB. Please see below. I do no have 10 reputations to post images. Hence I am giving an external link.
1) The initial form
http://postimg.org/image/qiojxjrcx/
2) Clicking the plus symbol, user can add more fields
http://postimg.org/image/zaetpokbx/
3) The fields added dynamically using Jquery have unique id's and a class. The script below is for getting the values of Staff Name and Mobile Number
a) Script for Getting Staff Name
var addstaffname = new Array();
$('input[class="addstaff"]').each(function() {
addstaffname.push(this.value);
});
b) Script for Getting Mobile Number
var addstaffmob = new Array();
$('input[class="addstaffmob"]').each(function() {
addstaffmob.push(this.value);
});
I am getting the values by using the class for Staff Name and Mobile. And through ajax I am posting these values in PHP.
$.ajax({
type:"POST",
url:"../../ajax.php",
data:'addstaffname='+addstaffname+'&addstaffmob='+addstaffmob,
cache:false,
success: function(data)
{
alert(data);
}
})
In ajax.php, I am storing these values into variables.
if(isset($_POST['addstaffname']))
{
$addstaffname = $_POST['addstaffname'];
$addstaffmob = $_POST['addstaffmob'];
$addstaffnameexploded = explode(',',$addstaffname);
$addstaffmobexploded = explode(',',$addstaffmob);
}
I am using explode as I have multiple values and all the values I get are CSV's from Jquery. I have a table called staff with three columns, staff_id,staff_name,staff_mobile and staff_id is PK and Auto Increment. My question is how do I insert staff name and mobile in the same row. Lets say we got staff name as A,B,C and mobile numbers as 100,200,300 from the form, I need to insert into MySQL DB with these values. So A will have mobile 100, B will have 200 and so on... If I had only one explode, I could easily use foreach loop and iterate. Very simple. I am going mad on how to insert data with this scenario. Any help will be highly appreciated.
I think the best way would be to create a form and use an array in the input
<input type="text" name="addstaffname[]" value="" />
<input type="text" name="addstaffmob[]" value="" />
then send the entire form using ajax
$("#form").ajaxForm({url: 'server.php', type: 'post'});
(ajaxForm is a jquery plugin ajaxForm)
and when you collect the data in php, you'll just have to do a foreach one of its key variables, some like this.
$addstaffname = $_POST['addstaffname'];
$addstaffmob = $_POST['addstaffmob'];
foreach($addstaffname as $key=>$name){
echo "Your name is " . $name . " and your phone is " . $addstaffmob[$key];
}
obviously you need to make a cast to vars, for sql injection or etc

JQuery var to form POST for PHP

To start off, sorry if this is a duplicate, or explained already. I've read a minimum of 15 other topics that I assumed are similar to mine, yet I haven't had any success in getting it to work.
I currently have a form that is action="submit.php". The form is an order form (see Jfiddle link at bottom of post). Inside submit.php I'm making an array of all $_POST values. That works great. Now the problem:
On the forum page (where user inputs), I have the following JQuery script that calculates totals. There are 3 types of totals (all this is clear in the JFiddle). The 3rd total, called "overallTotal", takes the sum of all "grandTotal"s and as of now, puts in #overallTotal ID. I need that number to be included in the form submission (i.e., so it is accessible by $_POST).
Thanks in advance, and sorry again if this is repetitive.
JSFiddle: http://jsfiddle.net/rc694dzL/
function oninput(e) {
// process this row first
var row = $(e.target).closest("tr");
// explicitly cast to a number
var quantity = +$(e.target).val();
var price = +row.find(".val1").text();
var output = row.find(".multTotal");
var total = price * quantity;
output.text(total);
// now calculate total
var subtotal = 0;
var table = $(e.delegateTarget);
table.find(".multTotal").each(function () {
subtotal += (+$(this).text());
});
table.find(".grandTotal").text(subtotal);
// now calculate overall total
var overallTotal = 0;
$(document).find(".grandTotal").each(function () {
overallTotal += (+$(this).text());
});
$('#overallTotal').text(overallTotal);
Add a hidden input in your form like this
<input type="hidden" name="overallTotal" id="overallTotalInput">
and set the value from javascript like this
$('#overallTotalInput').val(overallTotal);
Now when submitting the form, the value will be stored into $_POST['overallTotal']
Add some hidden fields in the form, and then populate the values with jquery.
Edit: tweaking your Fiddle now with an example: http://jsfiddle.net/dozecnp6/1/
1) Added the hidden input in the form:
<input type="hidden" name="OverallTotal" id="overallTotalField">
2) Added a bit to your oninput() function:
$('#overallTotalField').val(overallTotal);
in this fiddle i can use type="text" you can change it to type="hidden"
check this
fiddle

array not working for dynamic form field

I've found most of the pieces i've needed for this form (making the fields dynamic, etc.) however now the array part of this doesn't seem to work to be able to submit correctly.
what i'm trying to accomplish:
a form with a select field that can be duplicated dynamically and then be submitted as a part of the form to it's own table. so if we add and choose three people in the one form, it submits to it's own attending table with a foreign key back to the event the form is for. had to make it dynamic because we'll never know for sure how many people will be attending said event, but it has to happen all in one form. just because it does. my boss says so.
here's my javascript for the add another field button:
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the id value of the input inside the new element
newElem.children(':first').attr('id', 'attendee' + newNum).attr('name', 'attendee[' + newNum + ']');
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 5 names
if (newNum == 6)
$('#btnAdd').attr('disabled','disabled');
});
here's what the field starts out as in the form:
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<select name="attendee[1]" id="attendee1" style='float:right;margin-right:4.5%;'>
<option value=''>Please choose one...</option>
<?php
while($row_attendees = mysql_fetch_assoc($res_attendees)){
$attendee_id = $row_attendees['attendee_id'];
$attendee_name = $row_attendees['name'];
echo "<option value='".$attendee_id."'>".$attendee_name." </option>";
}
?>
</select><label style='width:100px;display:inline-block;line-height:28px;' for="attendee">Attendee</label>
</div>
I'm getting all the things to change correctly. all of the select inputs are being id'd and name'd correctly. the div is being updated the same. all of that works correctly. what doesn't is when i go to submit. here's my php:
foreach($_POST['attendee'] as $attendee){
$sql_attendees = "INSERT into marketing_calendar.attending (event_title, attendee_id) VALUES ('".$_POST['title']."','".$attendee."')";
$res_attendees = mysql_query($sql_attendees) or die(mysql_error());
}
all the tutorials i used to pull this together show this as correct. however it doesn't work. i'm only getting whatever the first dropdown is, and nothing else is populating into the array. at least that's all it shows/submits if i run the form or echo the attendee variable in the foreach statement. PLEASE HELP! :)
thanks a ton in advance.
UPDATE
I have tried a few ways discussed with another user to display the array for $_POST['attendee'], however it still just shows 1 id in the array, and not however many fields i've actually added. I've also tried removing the number from the array in the select's name attribute. so it would just be name='attendee[]' instead of name='attendee[1]' and so on. this also doesn't help any. can someone please help with why my dynamically added fields aren't being added to the array?
I put your code into a JSfiddle, here: http://jsfiddle.net/rv8Mv/1/
It looks like the selects are being added correctly. You can check by clicking the "Submit" button, which shows a data string of what will be submitted to the server.
One thing you might want to check, is to make sure you are enclosing all the select elements inside a <form> element, which you didn't include in your question.
I think your problem is in the PHP code on the server.
On the server, make sure you are receiving all the variables by using this code:
<?php
foreach($_POST as $key => $value){
error_log($key.' -> '.$value;
}
?>
Then check your error log to see the names and values for all the POST variables.
You are probably not referencing the POST variables correctly in your current PHP code.
You should change your sql to look like this:
foreach($_POST['attendee'] as $attendee){
$sql_attendees = "INSERT into marketing_calendar.attending (event_title, attendee_id) VALUES ('".$_POST['title']."',".$attendee.")";
$res_attendees = mysql_query($sql_attendees) or die(mysql_error());
}
Your attendee_id is an int column. You were wrapping the column content with single quotes, which denotes a string. This would result in your attendee_id being null if your column is defined as nullable.

Using one <form>'s selection to feed into another <form>?

From within php, I have a large html <form> filled out with lots rows of patient info from a postgres database. When a doctor double-clicks on a row, it sets a var in $_POST and invokes another php script to read up and display specific info about that row from the database. This all works.
But there are now so many rows of patient data that the doctors don't want to scroll and scroll to find the patient rows they're looking for, they want a patient prefilter <form> so that a click on an element in it will result in the large display filtered to just that patient's rows.
What's a basic approach to doing this? I'm a newb; I'm currently using html, php, and some javascript.
Make a second form with whatever options you'd like to filter on, this part will be specific to your data but you want something like
<form id="search-form">
<label>Name:</label><input type="text" name="patient-name"></input>
</form>
You'll need to build a query string (and make sure you use GET, because that will make things easier for you). This will require tweaking if you want to use radio buttons, or something similar, but here's the general idea:
function getSearchParameters () {
var form = document.getElementById('search-form');
var inputs = form.getElementsByTagName('input');
var result = '';
var i;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value) {
result += "&" + inputs[i].name + "=" + inputs[i].value;
}
}
return result;
}
In the onClick handler for your patient data links, you'll call this function and append its result to your query string:
element.onclick = function () {
var patientDataUrl = '/patients.php?param1=someValue';
patientDataUrl += getQueryParameters();
/* then do your ajax stuff as normal */
};
Then on the server side, within patients.php simply check for the presence of the search fields i.e.
if(isset($_GET['patient-name'])) {
$patient_name = mysql_real_escape_string($_GET['patient-name']);
$query = "SELECT * FROM `patients` WHERE `patient_name`='$patient_name';";
} else {
$query = "SELECT * FROM `patients`;";
}
(make sure you sanitize the string!)
I'd recommend considering a JS framework to make your life much easier (for instance, jQuery would allow you to send this via POST or easily serialize it into a GET query string via .serialize())

Dynamically populating HTML DropDown controls using AJAX and PHP

To dynamically fill DropDown controls on my HTML Form, I have written code that makes AJAX call to a .php file. This .php file populates the DropDown control with a single column value.
In this whole process, three files play the role.
(1) A HTML file that contains the entry form,
(2) A .js file containing basic AJAX code, and
(3) A .php file containing code to populate the DropDown control on my HTML form.
Below, I am giving the necessary code of all the three files respectively. The DropDown is not populating, therefore, I want to know the necessary corrections needed in the below given code.
Please note that the MakeRequest function in the .js file, accepts few arguments. These arguments are:
(1) HTML DropDown control name,
(2) Entire Sql Query.
(3) The ID column in a MySQL table.
(4) The actual column whose values need to be populated in the DropDown control.
In this context, for example, I am referencing a MySQL table named: "ElectionCategoryMaster", that comprises of following columns:
(1) ecID Int P.K
(2) ecName varchar
I am passing ID column as a argument so that I can retrieve this ID value when the user selects an ecName from the DropDown. This, ecID, will be stored in a different table.
[Code: HTML file]
<td onactivate="javascript: MakeRequest('inCategory','SELECT * FROM electioncategorymaster', 'ecid', 'ecname');">
<select id="inCategory" name="inCategory" class="entryFormInputBoxColor">
</select>
</td>
[Code: .js file] [AJAX]
function MakeRequest(DropDownName, SqlQuery, IdColumnName, DisplayColumnName)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "filldropdown.php?DropDownControlName = " + DropDownName + "&SqlQuery = " + SqlQuery + "&IdColumnName = " + IdColumnName + "&DisplayColumnName = " + DisplayColumnName, true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('ResponseDiv').innerHTML = response;
}
[Code: .php file] [To populate the desired DropDown control]
<?php
//Get values
$dropdownControlName = $_GET['DropDownControlName'];
$sqlQuery = $_GET['SqlQuery'];
$idColumnName = $_GET['IdColumnName'];
$displayColumnName = $_GET['DisplayColumnName'];
echo "dfddddf";
dbconnection::OpenConnection();
$result = dbaccess::GetRows($sqlQuery);
// JavaScript code to populate the DropDown.
echo "<select name='". $dropdownControlName ."'>";
echo "<option>Select</option>";
while($row=mysql_fetch_array($result))
{
echo "<option value=<?=". $row[$idColumnName] ."?>><?=". $row[$displayColumnName] ."?></option>";
}
echo "</select>";
dbconnection::CloseConnection();
?>
I believe the javascript is the source of the problem. Let me explain:
The function HandleResponse() always fills in the same ID. The variable DropDownName from your MakeRequest() function isn't passed anywhere to your HandlResponse() function. Try to add this argument, it should work better.
Apart from that, using MySQL queries directly inside your javascript is a big security issue.
1) You tell people the inner structure of your database.
2) People can modify this request to retrieve anything they want! FROM your database!
NEVER user directly user input (and yes, the GET argument CAN be user input: it's a simple GET variable, everyone has access to it).
I once used javascript to generate a query string, but was able to leave off many important details such as table name and WHERE conditions. I also made sure to use mysql_real_escape_string on it, adding strings to the front and back server side to make a complete query string. It was much easier than trying to post arrays. I feel that this was a safe and easier alternative.

Categories