How to get array values from view (Codeigniter) - php

i would like to ask for your help to solve my problem. Your help is kindly appreciated.
My question is i have two inputs type which are array ( <input type='text' name='cost[]'> and <input type='text' name='price[]'> ) in view. Both inputs type are within a foreach statement. Let's say foreach from a table of database that has 3 records. So, from the view of web browser it requires user to input 3 times on the cost and price fields for every record. In my controller, i want to compare user input as below
-price[1] cannot be more than cost[1]
-price[2] cannot be more than cost[2]
-price[3] cannot be more than cost[3]
by using if else statement. How am i going to code in my controller so that price[1] is only compared to cost[1], price[2] is only compared to cost[2] and price[3] is only compared to cost[3].Below is my code in my controller, but cannot work.
$cost = $this->input->post('cost');
$price = $this->input->post('price');
if ($price > $cost)
{
echo "Rejected";
}
else
{
echo "Accepted";
}

You will need to loop over all the values.
My Codeigniter is a little rusty but I believe $cost and $price should both be arrays. Some something simple like this;
foreach ($price as $key => $value) {
if ($value > $cost[$key] ) {
echo "Rejected";
} else {
echo "Accepted";
}
}
If you want all to be valid then you could just break on the first rejected value. Otherwise you loop through all and warn the user about the invalid ones?

Please try the code below.
For demo: Demo URL
<?php
//$cost = $this->input->post('cost');
//$price = $this->input->post('price');
//Suppose I have added dummy values in these variable as you received from view.
$cost = array(1,2,3);
$price = array(3,4,1);
//as you mentioned each one cost have price like $cost zero index compared with $price zero index.
$i = 0;
foreach($cost as $cos){
if ($price[$i] > $cos)
{
echo "Rejected";
}
else
{
echo "Accepted";
}
$i++;
}
?>

Related

How to count number of subarrays of one specific subarray?

I have loop that is saving data into multidimensional array.
$array = array();
for($i=0;$i<100;$i++) {
for($j=0;$j<100;$j++) {
if ($value1 != 0) {
$array[$i][$j]['key1'] = $value1;
$array[$i][$j]['key2'] = $value2;
$array[$i][$j]['key3'] = $value3;
}
}
}
Sometimes there may be no values to save for specific $j key, so before listing I would like to count the number of $j keys of each $i key.
I was trying do that in loop like that but it's not working:
for($i=0;$i<100;$i++) {
if (count($array[$i]) > 0) {
for($j=0;$j<count($array[$i]);$j++) {
echo $array[$i][$j]['key1'];
echo $array[$i][$j]['key2'];
echo $array[$i][$j]['key3'];;
}
}
}
}
I've seen many topics about counting arrays, but nothing similar to my problem.
Thanks in advance for any help.
EDIT:
As I looked into the comments I realized myself that indeed I've made mistake in the question, this is because I was writing the post very late, after many hours of work. Sorry.
The proper array reading code (that is representing my need) is:
for($i=0;$i<100;$i++) {
if (count($array[$i]) > 0) {
echo "table header";
}
for($j=0;$j<count($array[$i]);$j++) {
echo $array[$i][$j]['key1'];
echo $array[$i][$j]['key2'];
echo $array[$i][$j]['key3'];
}
}
As you see now I need to know if there are any data for each $i because table header is to be generated (or not) according to that.

Creating a border on last table row of a dynamic created table via php out of a database

Good evening,
I'm trying to find a function, where I can border the last table row from a dynamic created table.
<?php
session_start( );
echo '<br><br><br><h1 class="HLast">Your last order</h1>';
if( isset( $_SESSION['oldSession']) === true ){
$price = 0;
$resultsetOldOrder = $dbr->query( ' SELECT sn.preis, sn.name from food_order fo, speisen_neu sn
where fo.SID = "'.$_SESSION['oldSession'].'"
and sn.Artikelnummer = fo.artikelnummer ' );
if( $resultsetOldOrder == true){
echo '<table class="LastText">';
foreach( $resultsetOldOrder as $row ){
echo '<tr><td>'.$row['name'].'</td><td>'.$row['preis'].'</td></tr>';
$price = $price + $row['preis'];
}
echo '<tr><td>Total</td><td>'.$price.'</td></tr></table>
<table class="LastButton"><tr><td><form action = "printBill.php" method = "post">
<input type = "hidden" name = "oldOderID" value ="'.$_SESSION['oldSession'].'">
<button type = "submit">Print bill</button></form></tr></table>';
}else{
echo 'You have no last order';
}
}
?>
This one up here is my code. It works fine.
In a normal table i would simply try to give the last td a class and set a border around. But this is not possible here and I can't find anything in the web aswell.
Hope you can help me, thanks.
Well, while there's a better way to do this with css, to do this without making much changes to your codes, you can count the total number of rows in $resultsetOldOrder and then check within the loop if the current row is the last one.
if( $resultsetOldOrder == true){
$last_index = count($resultsetOldOrder) - 1;
echo '<table class="LastText">';
foreach( $resultsetOldOrder as $index => $row ){
if($index == $last_index) {
//This is the last row, do whatever you want
}
echo '<tr><td>'.$row['name'].'</td><td>'.$row['preis'].'</td></tr>';
$price = $price + $row['preis'];
}
echo '<tr><td>Total</td><td>'.$price.'</td></tr></table>
<table class="LastButton"><tr><td><form action = "printBill.php" method = "post">
<input type = "hidden" name = "oldOderID" value ="'.$_SESSION['oldSession'].'">
<button type = "submit">Print bill</button></form></tr></table>';
}else{
echo 'You have no last order';
}
Of course this is assuming $resultsetOldOrder array is indexed 0 to x. If its not, you can set $i = 0 before the loop and check inside the loop if $i == $last_index then do $i++.
I hope this helps.
With CSS you can select the last element of a type.
Take a look at this.
So in your case, you would do
tr:last-of-type {
//your styles here
}

How to insert value of dynamic form fields in database iusing code in php

I have a problem in trying to store database values in their respective rows inside the database using dynamic form fields. I have provided here the screenshots of my codes and outputs.
This is my script in adding dynamic form fields in which the form is located in a separate file named load_work_experience_form.php
This is the html code for the form I have appended in the my script to add a dynamic form fields
This is the look of my dynamic form fields
This happens to be the wrong output inside the database in which data values do not store in their proper record. I am attempting to insert 2 records of work experience but it seems that it has created 4 records.
The source code for adding into the database is supplied below. Kindly help me in fixing this problem. Thanks. More power:
<!--ADD WORK EXPERIENCE TO DATABASE -->
<?php
require'../admin/php/db_connection.php';
if(isset($_POST['update_profile']))
{
if (isset($_POST['employer'])) {
foreach ( $_POST['employer'] as $value ) {
$values = mysql_real_escape_string($value);
$query = mysql_query("INSERT INTO tbl_work_exp (employer) VALUES ('$values')");
}}
if (isset($_POST['job_position'])) {
foreach ( $_POST['job_position'] as $value ) {
$values = mysql_real_escape_string($value);
$query = mysql_query("INSERT INTO tbl_work_exp (job_position) VALUES ('$values')");
}}
//some more codes here for Work From and To. This website does not accept alot of codes. But the codes here are just like the ones at the top.
}
?>
<!--ADD WORK EXPERIENCE TO DATABASE -->
In the case that you have every time the same fields with dynamic rows:
<!--ADD WORK EXPERIENCE TO DATABASE -->
<?php
require'../admin/php/db_connection.php';
if(isset($_POST['update_profile']))
{
if (isset($_POST['employer'])) {
for ($i = 0, $nCount = count($_POST['employer']); $i < $nCount; $i++) {
$employer = mysql_real_escape_string($_POST['employer'][$i]);
$job_position = mysql_real_escape_string($_POST['job_position'][$i]);
$query = mysql_query('INSERT INTO tbl_work_exp (´employer´, ´job_position´) VALUES (´' . $employer . '´, ´' . $job_position . '´)');
}
}
}
?>
<!--ADD WORK EXPERIENCE TO DATABASE -->
You must add there the other fields also...
The problem of your logic is that you do for every field a insert but you need only one insert for one row.
And please don't use mysql library in php, it is better to use mysqli
Your problem is that you pass each value separately. I strongly suggest to change your HTML markup to group each value, but that's not the goal here. As for your current problem, this is a quick solution that can help you through. Picking up from your current code:
<?php
if (isset($_POST['update_profile'])) {
$profileFields = array('employer', 'job_position');
$profiles = array();
foreach ($profileFields as $field)
{
if (isset($_POST[$field])) {
foreach ($_POST[$field] as $key => $value) {
if (!isset($profiles[$key])) {
$profiles[$key] = array();
}
$profiles[$key][$field] = mysql_real_escape_string($value);
}
}
}
foreach ($profiles as $profile) {
$tableCols = implode(",", array_keys($profile));
$profileValues = implode("','", array_values($profile));
$insertQuery = "INSERT INTO tbl_work_exp ({$tableCols}) VALUES ('{$profileValues}')";
}
}
?>
Give or take a few tweaks or special treatment for each field. This is very generic code just to give you a guide.
Hope this helps
<?php
if(isset($_POST['Button_name'])){
for($i=0; $i<count($_POST['employer_name']); $i++){
$query="INSERT INTO table_name(employer_name,employer_age) VALUES ('".$_POST['employer_name']."','".$_POST['employer_age']."')";
$result=mysql_query($query);}}
<?php
$count_post_value = $_POST['first_name'] //this is value of text box //
for($i=0; $i<$count_post_value; $i++)
{
if(trim($_POST["first_name"][$i] && $_POST["last_name"] && $_POST["remarks"]!= ''))
{
$sql = mysql_query("INSERT INTO Table_name(first_name,last_name) VALUES('".$_POST["first_name"][$i]."','".$_POST["last_name"][$i]."')");
if($sql)
{
echo "<script>alert('Inserted Successfully');</script>";
}
else
{
echo "<script>alert('ERROR');</script>";
}
}
}
?>

Loop through multiple POST variables using dynamic naming

I hope this makes sense in relation to the title and what I'm trying to achieve, so here goes...
I have a form that displays between 1 to 30 fields to be entered - the number of fields is determined by the user at a previous stage (it will not always be the same amount).
If a user has 5 fields to fill out, they must all contain data - the same if they set 15 fields or 30 fields.
What I want to be able to do is loop through the POST variables in the form, make sure they are all set and either insert the data to the database, or display an error.
I was going to do 30 if statements with nested if statements:
if ($numberOfFields == 1){
if (!$_POST["field1_text"]){$error = 1;}
};
if ($numberOfFields == 2){
if (!$_POST["field1_text"]){$error = 1;}
if (!$_POST["field2_text"]){$error = 1;}
};
But this seems a very long winded way and I was wondering if anyone had any suggestions or pointers.
I was wondering if something like this would work:
for ($q = 1; $q <= $numberOfFields; $q ++){
if (!$_POST["field'".$q."'_text"]){
$error = 1;
}
}
But I'm getting an error referencing the variable/field name using the $q. Should this be [$q] or something else?
I'm struggling to find any answers, but probably not asking the right question, but any help would be appreciated.
Thanks
It could be done like this, using a foreach instead of a for:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$error = false;
foreach($_POST as $key => $value)
{
if(strpos($key, 'field') === 0)
{
if($value == '')
{
$error = true;
break;
}
}
}
if($error)
{
// not all fields have a value - show message
}
}
It would be much easier if you used an input array on the form, instead of manually populating the input names with a number concatenated. Example:
<input type="text" name="field[]" />
<input type="text" name="field[]" />
<input type="text" name="field[]" />
On the PHP side, simply loop over them:
foreach($_POST['field'] as $field)
{
if($field == '')
{
// error - doesn't have a value
}
}
Use this:
for ($q = 1; $q <= $numberOfFields; $q++){
if (!$_POST["field".$q."_text"]){
$error = 1;
}
}
In your own code you had weird extra '

Assigning variables based on string data

I have a inefficiently constructed form that is obviously sending one type of data per SELECT element. For simplicity's sake, here's an example.
The form posts data from 2 SELECT elements, but it actually needs to contain 3 pieces of data. To the user, the SELECTs do contain 3 pieces of data; one SELECT denotes quantity and the other SELECT denotes an item name AND a price using text between the OPTION tags.
So, the form is sending only $quantity and $itemname
In processing, I am trying to construct a bunch of IFs or a SWITCH to provide for the missing prices. Being that the string associated with $itemname is unique, I am trying to make a "key" that provides the price. My logic is, if $itemname contains "One Inch Nut" I could find for $price with something like:
if ($itemname = "Once Inch Nut;") { $price = .25; }
And if $itemname were something else, I would add another IF or IF else or CASE in a switch.
In fact, I am doing just that, yet when I select another OPTION from the SELECT, the $price and even the $item name are defined as the last "IF" in my stack of "IFs"
So if I were to select like, the 3rd item in a 20 item SELECT grouping, when it came time for me to use the variable (adding, echoing, whatever) I'd end up with the end of the "IF stack"
Obviously, my logic and understanding of IE ELSEIF ELSE is flawed.
Ideas on how to make this "Key" from a variable's string data?
Thanks,
Rob
See below for an abridged example of what I thought would work:
Suppose the form posts "cat" for $itemname and "3" for $qty
<?
$itemname = $_POST['specificitem'] ;
$qty = $_POST['quantity'] ;
if ($itemname = "cat;") { $price = 2.25; }
if ($itemname = "dog;") { $price = 1.25; }
if ($itemname = "hamster;") { $price = 3.25; }
if ($itemname = "parakeet;") { $price = 7.25; }
if ($itemname = "werewolf;") { $price = 122.25; }
echo $itemname;
echo "$"$price;
?>
Should yield: cat $2.25 ????
You need == to test:
if ($itemname == "cat;") { $price = 2.25; }
However, it is common to see switch used for this type of situation:
$itemname = $_POST['specificitem'] ;
$qty = $_POST['quantity'] ;
switch($itemname)
{
case "cat;":
$price = 2.25;
break;
case "dog;":
$price = 1.25;
break;
case "hamster;":
$price = 3.25;
break;
case "parakeet;":
$price = 7.25;
break;
case "werewolf;":
$price = 122.25;
break;
}
echo $itemname;
echo "$"$price;
I suggest you to use "table" approch for this code. Create an array representing price by item name. And get price in single line like following:
<?
$itemname = $_POST['specificitem'] ;
$qty = $_POST['quantity'] ;
## creating a price "table"
$item_prices = array(
'cat;' => 2.25,
'dog;' => 1.25,
## adding more is easy here
);
if (array_key_exists($itemname, $item_prices)) {
## get price in single line
$price = $item_prices[$itemname];
}
else {
## set some default price if item is unknown
}
echo $itemname;
echo "$",$price;
?>
Later you can use $item_prices to generate options for your select tag if you need.

Categories