counting help, to count the number of array in an array - php

I have a shopping cart which I got from Matthew Pennell(shopping cart tutorial), in his shopping cart script I would like to implement paypal. However I encounter a problem which I cant really solve. Since in his code he is doing a foreach loop , hence my paypal "item_name_" and "amount_" have to be variable. I need to count how many array is within an array . I tried it using count($content), it does give me number of array however , the result is increasing for every other row in my cart.
I.E
1 object return 1
2 object return 2 , 2
3 object return 3, 3 ,3
I'm wondering if I've missed out on other function, or is there a way to get only 1 result even if the actual return data is 3,3,3 .
Lastly for paypal_quantity is there such variable for add to cart?
<?php
$i = 1;
function checkout() {
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',', $cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
?>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart"></input>
<input type="hidden" name="upload" value="1"></input>
<input type="hidden" name="business" value="my_email.com"></input>
<?php
foreach ($contents as $id => $qty) {
echo $contents;
$sql = 'SELECT * FROM books WHERE id = ' . $id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
?>
<input type="hidden" name="item_name_<?php echo count($contents); ?>" value="<?php echo $title; ?>"></input>
<input type="hidden" name="amount_<?php echo count($contents); ?>" value="<?php echo $price; ?>"></input>
<input type="hidden" name="quantity" value="<?php echo $qty; ?>"></input>
<?php
}
?>
<input type="submit" value="PayPal"></input>
</form>

That is because these lines
<input type="hidden" name="item_name_<?php echo count($contents); ?>" value="<?php echo $title; ?>"></input>
<input type="hidden" name="amount_<?php echo count($contents); ?>" value="<?php echo $price; ?>"></input>
are inside the foreach loop and so if you loop twice, echo count($contents); runs twice and you get 22.

Cant believe im so stupid. Here have to say thanks alot for your all time and help. But i manage to solve this myself real easy.
foreach ($contents as $id => $qty) {
$rowid++;
$sql = 'SELECT * FROM books WHERE id = ' . $id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
echo $rowid;

I've looked at your code and made some suggested improvements. It looked like there was a bit of duplicated work going on, hopefully you can understand what I've done to help. It looks like this will probably work well to fix your issue at a minimum.
<?php
$i = 1; // not used in the below function.
function checkout() {
global $db;
// check for isset, it is more defensive and PHP is less inclined to issue a warning.
if( isset( $_SESSION['cart'] ) && $_SESSION['cart'] ) {
$items = explode( ',', $_SESSION['cart'] );
// array_count_values is pretty cool.
// it does exactly what your first for loop did.
$contents = array_count_values( $items );
?>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart"></input>
<input type="hidden" name="upload" value="1"></input>
<input type="hidden" name="business" value="my_email.com"></input>
<?php
foreach ($contents as $id => $qty) {
// echo $contents; <!-- this should echo 'Array' continually
$sql = 'SELECT * FROM books WHERE id = ' . $id;
$result = $db->query($sql);
$row = $result->fetch();
// extract is normally not the best practice, frequently it leads to accidental replacement of
// important variables -- if `books` had a `contents` column or quantity, that would be no good.
// so I've replaced it with what I expect are the keys to the array.
?>
<?php
/*
A caution about hidden inputs. They can be modified by the client, so if you were to, say,
trust the price listed below and your client had no scruples, your client could simply set
that value to, say, $0.01. Or worse, free!
*/
/*
I've changed up your input naming convention just slightly (it is easy to fix, but hear me
out first). You've used something which will render <name-1>_1, <name-1>_2... which means
that your $_POST (If you're buying something with this form, $_POST really is your better
bet) will have $_POST[<name-1>_1], $_POST[<name-1>_2]... In order to get all of the different
products grouped properly, you'll actually need to parse the $_POST indexes... it will get
messy. It's doable, but it will be annoying.
Instead, I put the naming convention <name-1>[1], <name-2>[2]. This means that $_POST will
have an array for each of the <names>. This means that you can do this:
$quantity = "";
$ammount = "";
foreach( $_POST[ 'item_name' ] as $key => $item )
{
$quantity = $_POST[ 'quantity' ][ $key ];
$ammount = $_POST[ 'ammount' ][ $key ];
// you now have all three quickly and easily with no string parsing! Set it and forget it!
}
*/
?>
<input type="hidden" name="item_name[<?php
// before you were using count($contents) here. That would mean that everything would have
// the same name and you'd only get one value back in $_REQUEST. I think you meant ID.
echo $id;
?>]" value="<?php echo $row['title']; ?>"></input>
<input type="hidden" name="amount[<?php echo $id; ?>" value="<?php
// ammount may not be your best choice of input name for something that refers to price.
// I know that when I look at it, I expect that to refer to quantity and not to cost
// and your first job as a developer is writing code which is as obvious as possible.
// But that is more stylistic than not so feel free to disregard
echo $row['price'];
?>]"></input>
<input type="hidden" name="quantity[<?php
// I took the liberty of adding id to this input as well -- otherwise you'd only have one
// quantity
echo $id;
?>]" value="<?php echo $qty; ?>"></input>
<?php
}
?>
<input type="submit" value="PayPal"></input>
</form>
<?php
}
}
?>

Related

Unable to get array data from form elements within a loop in CodeIgniter

So I have this form:
<?php echo flash_message_success('status_msg'); ?>
<?php echo form_open('students/mark_attendance/'.$session.'/'.$term.'/'.$class_id); ?>
<input type="checkbox" id="toggle_all" data-toggle="toggle" data-on="All Present" data-off="All Absent" data-onstyle="success" data-offstyle="danger" />
<?php
$i = 0;
foreach ($students as $s) {
$student_id = $s->id; ?>
<input type="hidden" name="student_id[]" value="<?php echo $student_id; ?>" />
<input class="bulk_select_present" type="radio" name="status[<?php echo $i; ?>]" value="Present" />Present
<input class="bulk_select_absent" type="radio" name="status[<?php echo $i; ?>]" value="Absent" />Absent
<input type="date" class="form-control" name="date" value="<?php echo set_value('date'); ?>" required />
<button class="btn btn-success" type="submit">Mark Attendance</button>
<?php echo form_close() //mark_attendance ?>
And this is the function which are process my form:
public function attendance($session, $term, $slug) {
$class_details = $this->common_model->get_class_details_by_slug(school_id, $slug);
$page_title = 'Attendance: ' . $class_details->class;
$this->admin_header($page_title, $page_title);
$data['session'] = $session;
$data['term'] = $term;
$data['class_id'] = $class_details->id;
$data['slug'] = $slug;
$data['students'] = $this->common_model->get_students_list_by_class($class_details->id);
$this->load->view('admin/students/attendance', $data);
$this->admin_footer();
}
public function mark_attendance($session, $term, $class_id) {
$this->form_validation->set_rules('date', 'Date', 'trim|required');
$this->form_validation->set_rules('student_id[]', 'Student ID', 'trim');
$student_id = $this->input->post('student_id', TRUE);
$status = $this->input->post('status', TRUE);
$date = $this->input->post('date', TRUE);
$slug = $this->common_model->get_class_details($class_id)->slug;
if ($this->form_validation->run()) {
for ($i = 0; $i < count($student_id); $i++) {
$d_id = $student_id[$i];
$d_status = $status[$i];
//check if student was marked absent or absent
if ($d_status == 'Present') {
$this->students_model->mark_student_present($session, $term, $class_id, $d_id);
} else {
$this->students_model->mark_student_absent($session, $term, $class_id, $d_id);
}
}
$this->session->set_flashdata('status_msg', "Attendance marked successfully");
redirect('students/attendance/'.$session.'/'.$term.'/'.$slug);
} else {
$this->attendance($session, $term, $slug); //reload page with validation errors
}
}
Problem is, the data won't get submitted to the database (my model is working fine, i tested it). Some checks revealed that $student_id is not parsed as an array (I tried checking using is_array function and it returned false). I have no explanation for this behavior, I did a similar implementation in another module and it works fine. I have practically turned the function inside out but the problem persists. I wonder what I'm doing wrong. Would appreciate if someone could point me in the right direction.
Note: the above is a simplified version of the code, I removed what I felt isn't necessary for this question.
you can't echo an array in php. The suggested way is that you should convert the array into json object then store the json object as string in hidden field then when you submit the form should decode the json object then will get an array.

Working with checkbox from form array in php

Am looping products out from product table to add them to cart table. only the selected product by checking the checkbox should be added, but if you select, the selected ones do not correspond..
HERE IS THE HTML GETTING THE PRODUCTS OUT
<html>
<form action="#" id="" class="horizontal-form" method="post">
<?php
$LISTP = "SELECT * FROM products ORDER BY id";
$sn = 0;
$stmt = $pdo->prepare($LISTP);
$stmt->execute();
while($list = $stmt->fetch(PDO::FETCH_ASSOC)){
$sn = $sn + 1;
$ID = $list['id'];
$NAME = $list['name'];
?>
<input type="checkbox" name="slected[]" class="checkboxes" value="1" />
<input type="hidden" name="productid[]" class="" value="<?php echo $ID;?>" />
<input type="text" name="name[]" class="" value="<?php echo $NAME;?>" />
<?php }?> </form>
<?php
// now when we submot the form
$slected = $_POST['slected'];
$prod = $_POST['productid'];
$name = $_POST['name'];
foreach($prod as $key => $product){
if($slected[$key]>0){
echo $product.' '.$name[$key].' '.#$slected[#$key].'--<br>';
}
// the problem is here, if you check all product it will work well, but if you check the second one
// it would echo the second one giving it the name of the first one which was not checked at all
?>
I used to do this the same way in the past, and have discovered what I think is a better way. Rather than having a hidden input that stores the ID, just use the ID as the index for all of the form variable keys:
<input type="checkbox" name="slected[<?php echo $ID; ?>]" class="checkboxes" value="1" />
<input type="text" name="name[<?php echo $ID; ?>]" class="" value="<?php echo $NAME;?>" />
Then, your PHP can be simplified:
// now when we submot the form
$slected = $_POST['slected'];
$name = $_POST['name'];
foreach( (array)$slected as $ID => $on ) {
echo $product . ' ' . $name[$ID] . ' ' . $ID . '--<br>';
}
So - basically, your $slected variable will contain an array of only items that are selected, AND you have the product ID built in to the $slected array.

Trying to store form input to array

I am trying to save form data to an array so I can display it in a table later. The problem I am having is that when I click the submit button and it reloads using php_self it seems to initialize the variables everytime. Here is an example of what I am trying to do.
<?php
// if first time initialize variables
if (!isset($i)) {
echo "in initialize section<br />";
$i = 0;
$itemno[] = "";
$desc[] = "";
}
if (isset($_POST['submitbtn'])) {
$itemno[$i] = $_POST['item'];
$desc[$i] = $_POST['desc'];
echo "Item# = " . $itemno[$i] . "<br />";
echo "Desc. = " . $desc[$i] . "<br />";
$i += 1;
echo "i = $i";
var_dump($itemno);
var_dump($desc);
}
?>
<form id="submititem" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="submit" >
<input name="item" placeholder="Enter item #" size="18" />
<input name="desc" placeholder="Enter Description" size="18" />
<input name="submitbtn" type="submit" value=">">
</form>
Thanks
Ralph
The issue you're having is that PHP starts "fresh" with every page load. You'll need to store the data somewhere if you want to preserve your array over several submissions. Session or a database are two of the commonest ways of doing this.
Here's how you might do it with session:
<?php
session_start();
$items = isset($_SESSION['items']) ? $_SESSION['items'] : array();
$descriptions = isset($_SESSION['descriptions']) ? $_SESSION['descriptions'] : array();
// your logic here...
$_SESSION['items'] = $items;
$_SESSION['descriptions'] = $descriptions;
Note that if your array is likely to get very big or if you have very many users, you'll probably want to use a database to store the item/description information.
You have to deal with session
$_SESSION['itemno'][$_SESSION['i']] = $_POST['item'];

Is it possible to have multiple "values" posted from a HTML form (checkboxes)?

I am developing an ordering page in PHP for some products. The user needs to be able to select multiple types of products, so checkboxes will be necessary in the HTML form.
I've established an array for the checkboxes via the "name" attribute.
My problem is, I want to display what the user has selected on a confirmation page, so I'd like the "value" of those checkboxes to ultimately return a product name AND a product price. As far as I can tell I'm going to be stuck with one value only, so I've attempted to get around this:
<?php
//variables for the array and the count
$parray = $_POST['product'];
$pcount = count($parray);
//arrays for each product's information; i've only listed one for simplicity
$br = array("Big Red", 575);
/*The idea for this was for each product ordered to add a line giving the product information and display it. When the $key variable is assigned, it is stored simply as a string, and not an array (yielding [0] as the first letter of the string and [1] as the second), which I expected, but my general idea is to somehow use $key to reference the above product information array, so that it can be displayed here*/
if (!empty($parray))
{
for ($i=0; $i < $pcount; $i++)
{
$key = $parray[i];
echo "<tr><td height='40'></td><td>" . $key[0] . "</td><td>" . $key[1] . "</td></tr>";
}
}
?>
Is there anyway to make my $key variable actually act as if it is the array's name it is set to?
If not, is there any good way to do this?
So in your HTML table, you'll need to render each checkbox like this:
<input type="checkbox" name="selectedIDs[]" value="$key" />
where $key is the item number.
Then, in your PHP, you'll have a $_POST["selectedIDs"] variable, which is an array of all the item numbers that were checked.
Assuming you've got a product list array like this:
$products = array( 1 => array("Big Red", 575), 2 => array("Spearmint", 525));
You can then print a list of the selected products using a loop like this:
for($i = 0; $i < count($_POST["selectedIDs"]); $i++) {
$key = $_POST["selectedIDs"][$i];
$product = $products[$key];
echo "<tr><td height='40'></td><td>" . $product[0] . "</td><td>" . $product[1] . "</td></tr>";
}
The only real difference between this and what you wrote is that my $products array is two-dimensional, and my $key is used to grab the relevant product from the $products array.
You can give the value of the options the value of the ID of the corresponding item. Then you'll receive an array of ID's, which you can then again map to the $br array, where you look up the name and price of an item by its ID. You could use the array key as ID, so:
<!-- Form: -->
<input type="checkbox" name="product[]" value="1" />
<input type="checkbox" name="product[]" value="..." />
<input type="checkbox" name="product[]" value="15" />
[...]
<?php
$product = array();
$product[1] = array('name' => "Big Red", 'price' => 575);
$product[...] = array('name' => "...", 'price' => ...);
$product[15] = array('name' => "Small Green", 'price' => 475);
foreach ($_POST['product'] as $pId)
{
echo $products[$pId]['name'] . " costs " . $products[$pId]['price'];
}
?>
If of course your array originates from a database, you can use the table's ID's as values for the checkboxes. You could then implode the $_POST['product'] (of course after escaping it) with a comma, and use it in a SELECT ... WHERE ID IN ($productIds) query.
If i'm understanding you correctly, you'll have checkboxes something like this:
<input type="checkbox" name="product_id[]" value="1">Product #1<br/>
<input type="checkbox" name="product_id[]" value="2">Product #2<br/>
<input type="checkbox" name="product_id[]" value="3">Product #3<br/>
That should post whatever is checked as an array to your server.
gen_paper1.php
<div style="overflow: auto; height: 500px; border: 1px solid;">
<form action="" method="post">
<fieldset style="font-size: 15px; font-weight: bolder;">
<h4><u>Your Existing Header's are listed below</u> </h4>
<hr / >
<?php
$xhdr = mysql_query("SELECT * from s_user_header ORDER BY 'ASC'");
while($rheader = mysql_fetch_array($xhdr)){
$h = $rheader['h_content'];
$hid = $rheader['h_id'];?>
<script>
$(document).ready(function(){
//$('input[type=checkbox]').val('<?php echo $hid ; ?>').tzCheckbox({labels:['<?php echo $h; ?>','<?php echo $h; ?>']});
//$('#c').tzCheckbox({labels:['<?php echo $h; ?>','<?php echo $h; ?>']});
$('').tzCheckbox({labels:['<?php echo $h; ?>','<?php echo $h; ?>']});
});
</script>
<table>
<td><input type="checkbox" id="c" name="u_hdr[]" value="<?php echo $hid; ?>"></td>
<td style="font-weight: bolder"><?php echo $h."<br />"; ?></td>
</table>
<?php } ?>
</fieldset>
</div>
gen_paper2.....3.....
i need all this values in further page, so have taken hidden variables
<input type="hidden" name="hstdid" value="<?php echo $stdid; ?>">
<input type="hidden" name="hsubid" value="<?php echo $subid; ?>">
<input type="hidden" name="hdifid" value="<?php echo $difid; ?>">
<input type="hidden" name="hmarks" value="<?php echo $t_marks; ?>">
<input type="hidden" name="h_hid[]" value="<?php echo $hh; ?>">
gen_paper4.php
$getstdid = $_POST['hstdid3'] ;
$getsubid = $_POST['hsubid3'] ;
$getdifid = $_POST['hdifid3'] ;
$gethmarks = $_POST['htmarks'] ;
$hdr= $_POST['h_hdrid'] ;
$h = implode($hdr);
<table>
<?php
$h1 = explode(",",$h);
count($h1) . "<br />";
for($i=0;$i<count($h1);$i++){
$h1[$i];
$xheader = mysql_query("SELECT * from s_user_header WHERE h_id = ".$h1[$i]);
while($row = mysql_fetch_array($xheader)){ ?>
<tr>
<td><b>
<?php echo $i + 1 . ".&nbsp&nbsp&nbsp"; ?>
</b></td><td>
<?php echo $header = $row['h_content'] . "<br />";
?></td>
</tr>
<?php
}
}
//echo $header; ?>
</table>

changing a lists sort order inline

I have a list
Each row has a common input field "sort_order" that's stored in MySQL db.
<input name="sort_order" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
I want to be able to change the sort order inline, without going into the edit form.
How do I get all the values into the database. I think I need to loop through each row adding the sort_order[row_id] and value to an array. But I am stuck on how to achieve this.
all the values are posting according to firePHP. sort_order[50] 1, sort_order[51] 2 etc.
New Attempt at explaining:
I have a list view with 2 input fields.
<input name="cat_id" type="hidden" value="<?php echo $cat['cat_id']; ?>" />
<input name="sort_order" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
I have a function that's called on post in the controller:
public function sortOrderUpdate(){
//collect the values of cat_id and sort_order from each input into a array
//$this->request->post['sort_order']
//$this->request->post['cat_id']
//send to the model
$this->model_cat->updateCatSortOrder($sortorderarray);
}
And the database model file function:
public function updateCatSortOrder($sortorderarray){
foreach((int)$sortorderarray as $sort){
$this->db->query("UPDATE cat SET sort_order='" . (int)$sort['sort_order'] . "' WHERE cat_id = '" . (int)$sort['cat_id'] . "'");
}
}
Whats the best way to achieve this?
Just use empty square brackets:
<input type="text" name="sort_order[]" value"<?php echo $sort_order; ?>" />
You can then access the input as an array, saving you from building it yourself. It'll be stored as $_POST['sort_order'] (or $_GET, depending on the method attribute specified in your <form> tag).
On a related note, you should probably escape $sort_order when echoing it:
<input type="text" name="sort_order[]" value"<?php echo htmlspecialchars($sort_order); ?>" />
i would not recommend using [ ] in html names.
<input type="text" name="sort_order_<?php echo $row_id; ?>" value"<?php echo $sort_order; ?>" />
say, you have 50 input fields, when posted, you can build an array this way:
$sortorder = array();
for($i=0; $i<50; $i++){
$sortorder[] = $_REQUEST['sort_order_' . $i];
}
Ok this seems to work:
<input name="cat_id[]" type="hidden" value="<?php echo $cat['cat_id']; ?>" />
<input name="sort_order[]" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
Controller:
public function updateCatSortOrder(){
$sortvals = $this->request->post['sort_order']; //$this->request->post same as $_POST
$row = $this->request->post['cat_id'];
$n = count($this->request->post['cat_id']);
$sortorder = array();
for($i=0; $i<$n; $i++){
$sortorder[] = array(
'cat_id' => $row[$i],
'sort_order' => $sortvals[$i]
);
}
$this->model_cat->updateCatSortOrder($sortorder);
}
Model:
//UPDATE CAT SORT ORDER
public function updateCatSortOrder($sortorder){
foreach($sortorder as $sort){
$this->db->query("UPDATE cat SET sort_order='" . $this->db->escape($sort['sort_order']) . "' WHERE cat_id = '" . $this->db->escape($sort['cat_id']). "'");
}
}

Categories