Input boxes in while loop - forms

I am wondering how I can differentiate the name on the input box in a while loop so when I post I get 2 separate values. Here is my code:
<form method="post" action="rewarded.php">
<?php
$nameqry="SELECT name FROM kids";
$names=mysqli_query($conn, $nameqry) or die ("Error could not execute name query: " . mysqli_error());
echo "<table>";
while($namerow=mysqli_fetch_array($names)) {
$name=$namerow["name"];
echo "<tr><td>$name will use <input type='text' name='points'> points.</td></tr>";
}
echo "</table>";
echo "<input type='submit' value='Submit'>";
?>
</form>

while($namerow=mysqli_fetch_array($names)) {
$name=$namerow["name"];
echo "<tr><td>$name will use <input type='text' name='points-<?php echo $name; ?>'> points.</td></tr>";
}
each time the code repeated in loop it gives you a different input name.
also you can use name="points[]"
it will return all names in a array

You could make the name a variable and change the variable on each loop.
$input_name_count = 1;
while($namerow=mysqli_fetch_array($names)) {
$name=$namerow["name"];
echo "<tr><td>$name will use <input type='text' name='".$input_name_count."'> points.</td></tr>";
}
Alternatively, if you don't want to use numbers (i.e. points1, points2, etc.or 1,2,3 etc.) make a list of names that you want.
$names_list = ['name', 'name 2', 'hippos'];
Then simply select the item you want from the list using a counter.
$counter = 0;
while($namerow=mysqli_fetch_array($names)) {
$name=$namerow["name"];
echo "<tr><td>$name will use <input type='text' name='".$names_list[$counter]."'> points.</td></tr>";
$counter++;
}

Related

Why am I getting this error when testing a Perl/CGI scipt on Padre?

Spent better part of 3-days writing a CGI script to handle the input form data from my HTML. Used Padre as an editor but now receive this error when running the script.
"uncaught exception from user code: "-T" is on the #! line, it must also be used on the command line at scipt.pl"
I'd like some pointers if anyone is willing to look over my code and offer guidance. This is my first endeavor into Perl and CGI. What I desire for endstate is a form a webuser enters data and then hits submit. After validation a page is sent back to the browser with information and errors if they exist. here is my code and thanks in advance!
HTML Code:
<html>
<head><title>My First CGI-PERL</title>
<!--Link to css for styling here-->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header>
<h1>Welcome to my first CGI-PERL Form submission</h1></header>
<br>
<p>Please Enter the following information in the fields and click
SUBMIT.</p>
<hr>
<br>
<div class="container1">
<form action="/cgi-bin/text.pl" method="post"> <!--script to process
this section-->
Item Number<input type="text" name="Item"><br> <!--Cannot be blank-->
Product Name<input type="text" name="Name"><br> <!--Cannot be
blank-->
Product Cost<input type="text" name="Cost"><br> <!--must be between .50 and $1000-->
Selling Price<input type="text" name="Price"><br> <!--price from 1.00 to 2000.00-->
Quantity on Hand<input type="text" name="Quantity"><br> <!--cannot be negative-->
</form></div>
<br>
<br>
<hr>
<br>
<h2>Choose A Product Category</h2> <!--must be one of the categories-->
<br>
<div class="container2">
<form action="/cgi-bin/radio.pl" method="post"> <!--name of script that handles this section-->
<input type="radio" name="letter" value="F">F<br>
<input type="radio" name="letter" value="H">H<br>
<input type="radio" name="letter" value="M">M<br>
<input type="radio" name="letter" value="C">C<br>
<input type="radio" name="letter" value="T">T<br>
<br>
</form></div>
<hr>
<br>
<div class="container4">
<form action="/cgi-bin/myfirstcgi.cgi" method="post"> <!--script to process submit and send a second page back-->
<input type="submit" name="submit" value="SUBMIT"><br>
</form></div> <!--close container 2-->
<!--Profit should be auto generated on the second page created by the script-->
</body>
</html>
Perl Script:
#!/usr/bin/perl
print "Content-type: text/html\n\n";
use strict;
use warnings;
use CGI qw(:standard);
print "<html><body>";
print "Thank you for submitting the form. <br>\n";
#return to html page with form
print "To go back to the form page click"; #how can i insert a link to the form page here
print "You chose item number ", param("Item")," \n";
print "The product name is ", param("Name"), " \n";
print "The Cost is ", param("Cost")," \n";
print "Selling Price ", param("Price")," \n";
print "Quantity on Hand is ", param("Quantity")," \n";
#scalar variables to hold form input data
my $item = param("Item");
my $name = param("Name");
my $cost = param("Cost");
my $price = param("Price");
my $category = param("Category"); #radio button chosen
my $quantity = param("Quantity");
my $profit = $cost - $price;
#radio buttons
my %categories = ("F", "H", "M", "C", "T");
#validation a category was chosen
my $categories = param("letter");
if (exists $categories{$category}) {
print "The product Category is $category";
}
else {
error ("You must select a category");
}
#validate input
if ($item eq "") {
error ("Field cannot be blank");
}
if ($name eq "") {
error ("Field cannot be blank");
}
if ($cost < .50 && $cost > 1000) {
error ("Invalid Entry Cost must be between $.50 and $1000");
}
if ($price < 1.00 && $cost > 2000) {
error ("Invalid Amount Please enter Price between $1.00 and $2000");
}
if ($quantity < 0) {
error ("Quantity cannot be negative number");
}
sub error {
my ($errormsg) = #_;
print "<h2>Error</h2>\n";
print "$errormsg<p>\n";
print "</body></html>\n";
exit;
}
Your homework should be done by you. But Since there is lot of syntax mistakes there I will try to help you.
First of all Bind all the elements inside the html into a single form with single submit button so that it can go to server in the form of query string in a single go.
Your html should be:
<html>
<head><title>My First CGI-PERL</title>
<!--Link to css for styling here-->
<!--<link rel="stylesheet" type="text/css" href="style.css">-->
</head>
<body>
<header>
<h1>Welcome to my first CGI-PERL Form submission</h1></header>
<br>
<p>Please Enter the following information in the fields and click
SUBMIT.</p>
<hr>
<br>
<div class="container1">
<form action="action.cgi" method="post"> <!--script to process
this section-->
Item Number<input type="text" name="Item"><br> <!--Cannot be blank-->
Product Name<input type="text" name="Name"><br> <!--Cannot be
blank-->
Product Cost<input type="text" name="Cost"><br> <!--must be between .50 and $1000-->
Selling Price<input type="text" name="Price"><br> <!--price from 1.00 to 2000.00-->
Quantity on Hand<input type="text" name="Quantity"><br> <!--cannot be negative-->
<br>
<br>
<hr>
<br>
<h2>Choose A Product Category</h2> <!--must be one of the categories-->
<br>
<div class="container2">
<input type="radio" name="letter" value="F">F<br>
<input type="radio" name="letter" value="H">H<br>
<input type="radio" name="letter" value="M">M<br>
<input type="radio" name="letter" value="C">C<br>
<input type="radio" name="letter" value="T">T<br>
<br>
<hr>
<br>
<div class="container4">
<input type="submit" name="submit" value="SUBMIT"><br>
</form></div> <!--close container 2-->
<!--Profit should be auto generated on the second page created by the script-->
</body>
</html>
Your cgi script I named as action.cgi and It should be like this for the above html from your approach. Whatever the error you had I tried to show it using commented lines.
#!/usr/bin/perl -T
print "Content-type: text/html\n\n";
use strict;
use warnings;
use CGI qw(:standard);
print "<html><body>";
print '<h1>"Thank you for submitting the form. <br>"\n';
#return to html page with form
print '<h2>To go back to the form page click Here.</h2>';#missing quotes
print "<hr><br><br>";
print "You chose item number ",param("Item")," <br>";
print "The product name is ", param("Name"), " <br>";print "The Cost is
", param("Cost")," \n";
print "Selling Price ", param("Price")," <br />";
print "Quantity on Hand is ", param("Quantity")," <br> ";
#scalar variables to hold form input data
my $item = param("Item");
my $name = param("Name");
my $cost = param("Cost");
my $price = param("Price");
my $category = param("Category"); #radio button chosen
my $quantity = param("Quantity");
my $profit = $cost - $price;
#radio buttons
my #categories = ("F", "H", "M", "C", "T");#better use array
#vali`dation a category was chosen
$category = param("letter");
if(grep { /$category/ } #categories) { # check if category exist in your predefined array
print "The product Category is $category \n";
}
else {
error ("You must select a category");
}
#validate input
if ($item eq "") {
error ("Field cannot be blank");
}
if ($name eq "" ){
error ("Field cannot be blank");
}
if ($cost < .50 && $cost > 1000) {
error ("Invalid Entry Cost must be between $.50 and $1000");
}
if ($price < 1.00 && $cost > 2000) {
error ("Invalid Amount Please enter Price between $1.00 and $2000");
}
if ($quantity < 0) {
error ("Quantity cannot be negative number");
}
#Error subroutine
sub error {
my $errormsg = shift;#you shouldn't assign array to variable
print "<h2>Error</h2>\n";
print "$errormsg<p>\n";
print "</body></html>\n";
}
If you really want to learn perl after basic understanding try to learn
perldsc,perlvar,perlref,perloo,perlobj
Padre runs Perl programs using a command like:
/usr/bin/perl <your_file.pl>
Taint checking requires deep changes to how the compiler works, so it needs to be turned on immediately after the compiler starts up. You have -T on the shebang line inside your program and that isn't parsed until after the compiler starts - too late for taint mode to be enabled. It would be confusing for Perl to start running your code not in taint mode when you think that taint mode has been turned on, so it halts execution with the error message that you have seen.
You can fix this by configuring Padre to run your code with as slightly different command:
/usr/bin/perl -T <your_file.pl>
In Padre choose Tools -> Preferences from the menu and then select the "Language - Perl 5" option. There is a text input labelled "Interpreter arguments". You can put your -T there and save the changes.
Also, I'll just reiterate my previous advice that using CGI in 2015 is ridiculous. Please take a look at CGI::Alternatives and switch to a more modern architecture.

Codeigniter - update table from form with checkbox

I'm trying to update a MySQL table with Codeigniter.
My model code is:
function update_customer_records($updatedrow)
{
$this->db->where('id',$this->input->post('id'));
$this->db->update('customers',$updatedrow);
}
My view is:
$attributes=array(
'name'=>'updatecustomer',
'id'=>'updatecustomer',
);
echo form_open('masterdata/manage_customers',$attributes);
?>
<table>
<tr>
<td> </td><td> </td><td>Customer Name</td><td>postalcode</td>
<tr>
<?php if(isset($records)) : foreach ($records as $row) : ?>
<tr>
<td>
<?php echo anchor('masterdata/customers_updated/'.$row->id, img(array('src'=>'images/delete_icon.png','border'=>'0','alt'=>'Delete'))); ?>
</td>
<td>
<input type=checkbox name="editcustomer[]" id="editcustomer[]" value="<?php echo $row->id ?>">
</td>
<td>
<input type="text" name="customername_<?php echo $row->id ?>" id="customername_<?php echo $row->id ?>" value="<?php echo $row->customer_name ; ?>" >
</td>
<td>
<input type="text" name="customername_<?php echo $row->id ?>" id="customername_<?php echo $row->id ?>" value="<?php echo $row->postalcode ; ?>" >
</td>
</tr>
<?php endforeach ; ?>
</table>
<input type="submit" value="Update Selected">
<?php else : ?>
<h2> No Records Found</h2>
<?php endif; ?>
<?php echo form_close(); ?>
My controller is :
function manage_customers()
{
$data['title']="Manage Customers";
//query model to get data results for form
$data=array();
if($query=$this->model_master_data->get_records()){
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_manage_customers",$data);
$this->load->view("master_data/view_master_data_footer");
$editcustomer = $this->input->post('editcustomer');
if(isset($editcustomer)){
//begin outputting id of selected checkbox
foreach ($editcustomer as $row) :
echo $row;
$updatedrow=array(
'id'=>$row,
'postalcode'=>'44444'
);
$this->model_master_data->update_customer_records($updatedrow);
endforeach;
}
I have two issues :
How do I stop the foreach from running if a checkbox has not been checked.
How do I pass the array to the model correctly so that the update runs?
Thanks in advance as always.
First of all I found two fields in the form with the same name and id (given below) and in one field you are setting it's value customer_name and in another you are setting postalcode.
<td>
<input type="text" name="customername_<?php echo $row->id ?>" id="customername_<?php echo $row->id ?>" value="<?php echo $row->customer_name ; ?>" >
--^^--
</td>
<td>
<input type="text" name="customername_<?php echo $row->id ?>" id="customername_<?php echo $row->id ?>" value="<?php echo $row->postalcode ; ?>" >
--^^--
</td>
So I think (probably) the name and id of the second field should be postalcode according to it's value.
Also you don't need to worry about foreach loop because the code inside the loop ll run only if there are checked check boxes on the form because unchecked check boxes won't be submitted but you can check and run the loop using following code
if( $this->input->post('editcustomer') != false )
{
foreach ($editcustomer as $row)
{
// code here
}
}
The if condition will return false if the editcustomer is not found or not submitted with the form. Also there is no id field in your form and in this case you can't use $this->input->post('id'), so if you need to check the check box id in the where clause of your model then you can use
In The controller :
if( $this->input->post('editcustomer') != false )
{
$this->load->model('model_master_data');
foreach ($editcustomer as $row_id)
{
$data = array( 'postalcode' => '44444' );
$this->model_master_data->update_customer_records( $row_id, $data );
}
}
I don't think you need to pass 'id'=>$row, because you probably don't wan't to update this field. Also you should use form validation to check the form input before updating the record (you may set the postcode field required to bound the user to enter a postcode).
In The Model :
function update_customer_records( $id, $data )
{
$this->db->where( 'id', $id );
$this->db->update( 'customers', $data );
}
So it'll do something like this (pseudo code)
update the customers table set `postalcode` = '44444' where `id` = $id
Update :
I think you can also use the update_batch.
In The controller :
if( $this->input->post('editcustomer') != false )
{
$data = array();
foreach ($editcustomer as $row_id)
{
$data[] = array( 'id' => $row_id, 'postalcode' => '44444';
}
$this->load->model('model_master_data');
$this->model_master_data->update_customer_records( $data );
}
In The Model :
function update_customer_records( $data )
{
$this->db->update_batch('customers', $data, 'id');
}
Duplicate topic with "Codeigniter update mysql table from form with CI" ?
how do I stop the foreach from running if a checkbox has not been checked.
You don't have to stop the foreach from running if a checkbox has not been checked.
Because $editcustomer variable only contain checkbox checked.
How do I pass the array to the model correctly so that the update runs?
Your model is wrong. It should be:
public function update_customer_records($updatedrow)
{
$this->db->update('customers', $updatedrow);
}
You don't need to write $this->db->where('id',$this->input->post('id')); (and it's wrong, because you can't use $this->input->post() in your model) because you already pass id in $updaterow.
Edit : I'm sorry, I read your code too quickly!
function update_customer_records($updatedrow)
{
$this->db->where('id',$this->input->post('id'));
$this->db->update('customers',$updatedrow);
}
...is correct. Alternatively, you can write it in a shorter way:
function update_customer_records($updatedrow)
{
$this->db->update('customers', $updatedrow, array('id' => $this->input->post('id')));
}

Joomla/Mootools capturing order of Sortables

I am trying to sort a list of database entries and then update the database with the new order in Joomla.
So far I've got mootools Sortables list with every <li> having two hidden <input> to track the entry's id and order. At the moment the order variable does not change and just reflects the original order.
I was hoping to capture the submit event and change the order variables to what they should now be and then send the request on, however I have no idea how to do this...
I have:
<li style="float:left">
<input type="hidden" name="o<?php echo $row->order; ?>" value="<?php echo $i; ?>" />
<input type="hidden" name="i<?php echo $row->order; ?>" value="<?php echo $row->lotid; ?>" />
Lot <?php echo $row->lot_name; ?><br />
<?php echo $row->address; ?>
</li>
And:
window.addEvent('domready', function(){
new Sortables('#order-grid', {opacity: 0.7});
form = document.id('adminForm');
list = document.id('order-grid');
form.addEvent('submit', function(e) {
var sortOrder = [];
list.getElements('li').each(function(li) {
sortOrder.push(li.retrieve... //Stuck!
});
});
});
Any help appreciated.
the doc pages are your friend. http://mootools.net/docs/more/Drag/Sortables
first off, i'd say save a reference.
var sortables = new Sortables(options)
then you can use the sortables.serialize() method to retrieve the new order. by default, serialization will return the element ids - but it takes an argument that is a function - so you can return whatever you like.
eg. to get an array of the new sort order, simply do
var newOrder = sortables.serialize(function(el, index) {
return el.get('data-id'); // or el.retrieve('id'); if you have one.
});
Finally, no need to do it on the submit event - you can just do something like:
var orderField = document.id("i_something_order");
new Sortables('#order-grid', {
onComplete: function() {
orderField.set('value', this.serialize(function(el) {
el.retrieve('id');
}).join(','));
}
});
note that retrieve implies you have used store beforehand. if it's a DOM attribute you are after, just do el.get('data-id') or whatever it is as suggested

Codeigniter How to Validate Multiple Text Input Array of the Same Name?

I'm building a reservation system where the user first selects how many persons, and then depending on that selection, ajax will populate the respective number of text input fields to get the name of the guests.
So my stripped down text input structure is such:
<input type="text" name="name[]" value="<?php echo set_value('name[]');?>"/>
<input type="text" name="name[]" value="<?php echo set_value('name[]');?>"/>
<input type="text" name="name[]" value="<?php echo set_value('name[]');?>"/>
And on my controller, the validate function is such:
$this->load->library('form_validation');
$this->form_validation->set_rules('name[]', 'Name', 'required|xss_clean');
So the thing that isn't working right is on submit, if I only entered a name on input 1, on the validated page, the errors will show for every input, at the same time, every input will have the same name i entered for input #1.
What am I doing wrong here ?
Just do it manually
$errors = "";
foreach($name as $n){
if(!$n){
$errors .= "Please fill in all names fields";
}
}

facebook graph api - search event

In the event search, the query searches only by the Event Name:
sample http://graph.facebook.com/search?q=party&type=event
Is there a way to query the Event Description? Or other fields ?
I tried to use until or since, but i get the same results
https://graph.facebook.com/search?q=party&type=event&until=today
https://graph.facebook.com/search?q=party&type=event&until=yesterday
FQL only accept search by event ID
The search returns the id's for all events returned in the search. Using https://graph.facebook.com/search?q=party&type=event&until=today&fields=id you can loop the id results to https://graph.facebook.com/eventid?access_token=yourapptoken to get array of the event which will include the description, name, image etc;
Live Sample for Page & Event Search here: http://shawnsspace.com/plugins/plugins.searcher.php
Refer to: http://developers.facebook.com/docs/reference/api/event/
Example Code: Assumes PHP-SDK 3.1.1 is installed on page.
Events https://graph.facebook.com/search?q=conference&type=event
<?php
$qi = urlencode($_GET['qs']);
if(!$_GET['qs']){
$qi = urlencode($_POST['qs']);
if(!$_POST['qs']){
$qi = "party";
}
}
$search = $facebook->api('/search?q='.$qi.'&type=event&limit=10');
foreach ($search as $key=>$value) {
$i=1;
foreach ($value as $fkey=>$fvalue) {
$i++;
if($fvalue[id]=="h"){
}else{
$id = $fvalue[id];
$searchResp = $facebook->api('/'.$id.'');
$name = $searchResp[name];
$location = $searchResp[location];
$desc = $searchResp[description];
$sTime = $searchResp[start_time];
$eTime = $searchResp[end_time];
echo $name. '<br />';
echo $location. '<br />';
echo $sTime. '<br />';
echo $eTime. '<br /><hr />';
}
};
};
?>
<form id="getsearch" method="post" action="yourpage.php">
<input type="text" value="" name="qs" id="searchbox" onclick="this.value='';" style="padding: 2px;" size="48">
<input type="submit" value="Search" style="padding: 3px;">
</form>
The search in Graph API for events is currently limited to the event name only; I don't believe there are plans to change this in the short term, unfortunately