After I get all the results from my DB, I added some extra data ('Prio')
I used the $_POST method and store the following result in an array:
array (size=4)
'gereed' => string 'gereed' (length=6)
1 =>
array (size=7)
'prio' => string '1' (length=1)
'res' => string '456' (length=3)
'base' => string '190203' (length=6)
'lot' => string '101' (length=3)
'split' => string '0' (length=1)
'sub' => string '0' (length=1)
'seq' => string '10' (length=2)
2 =>
array (size=7)
'prio' => string '2' (length=1)
'res' => string '456' (length=3)
'base' => string '180676' (length=6)
'lot' => string '10' (length=2)
'split' => string '0' (length=1)
'sub' => string '0' (length=1)
'seq' => string '30' (length=2)
3 =>
array (size=7)
'prio' => string '3' (length=1)
'res' => string '456' (length=3)
'base' => string '180676' (length=6)
'lot' => string '10' (length=2)
'split' => string '0' (length=1)
'sub' => string '0' (length=1)
'seq' => string '60' (length=2)
Now I have only 3 rows, but it could happen that I have 10 or more rows.
I want to display these data like I did with the while loop.
So that the loop will go trough the rows (1, 2, 3, xx) and I can just dispaly them for example like echo $row['prio'];
Maybe it is an easy question, but I'am still learning.
EDIT!
At the input part I get the Prio value. I want to update this value at the right row.
UPDATE VMSCHRIP_SIM SET OPERATION_PRIORITY = $_POST['prio'] WHERE BASE = $_POST['base'] AND RESOURCE = $_POST['res'] AND blablabla
something like that...
Here is a part of my code.
if ($result > 1) {
$i = 1;
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$TrCode = transactionCodeDirect($Employee, $row["WORKORDER_BASE_ID"], $row["WORKORDER_LOT_ID"], $row["WORKORDER_SPLIT_ID"], $row["WORKORDER_SUB_ID"], $row["SEQUENCE_NO"], $row["RESOURCE_ID"]);
if ($TrCode <> ""){
$actief = "<p class=text-success>Actief</p>";
}else{
$actief = "<p class=text-warning>Klaar om te starten</p>";
}
if($row["DESCRIPTION"] == ""){
$description = strtok(wo_description($row["WORKORDER_BASE_ID"], $row["WORKORDER_LOT_ID"], $row["WORKORDER_SPLIT_ID"]), '(**');
}else{
$description = $row["PART_ID"]." : ".$row["DESCRIPTION"];
}
if($row["PREV_OP"] == "" and $row["MAT_REMAINING"] == '0'){
$row["PREV_OP_COMPLETED_QTY"] = $row["CALC_END_QTY"];
}
?>
<a href="#" class="list-group-item">
<div style="text-align:left">
<div class="row">
<div class="col-lg-1">
<br>
<span class="fa-stack fa-1x">
<i class="fa fa-circle-o fa-stack-2x"></i>
<span class="fa fa-stack-1x"><?php echo $row["OPERATION_PRIORITY"];?></span>
</span>
</div>
<div class="col-lg-1">
<br>
<input type="text" name="<?php echo $i; ?>[prio]" class="form-control" value="" autofocus placeholder="Prio">
<input type="hidden" name="<?php echo $i; ?>[res]" value="<?php echo $row['RESOURCE_ID'];?>">
<input type="hidden" name="<?php echo $i; ?>[base]" value="<?php echo $row['WORKORDER_BASE_ID'];?>">
<input type="hidden" name="<?php echo $i; ?>[lot]" value="<?php echo $row['WORKORDER_LOT_ID'];?>">
<input type="hidden" name="<?php echo $i; ?>[split]" value="<?php echo $row['WORKORDER_SPLIT_ID'];?>">
<input type="hidden" name="<?php echo $i; ?>[sub]" value="<?php echo $row['WORKORDER_SUB_ID'];?>">
<input type="hidden" name="<?php echo $i; ?>[seq]" value="<?php echo $row['SEQUENCE_NO'];?>">
</div>
<div class="col-lg-4">
<b><?php echo $row["NAME"];?></b><br>
<?php echo $row["WORKORDER_BASE_ID"];?>/<?php echo $row["WORKORDER_LOT_ID"];?>.<?php echo $row["WORKORDER_SPLIT_ID"];?>-<?php echo $row["WORKORDER_SUB_ID"];?>:<?php echo $row["SEQUENCE_NO"];?><br>
Vorige bewerking: <?php echo $row["PREV_OP"];?><br>
</div>
<div class="col-lg-6">
<?php echo $description;?><br>
<?php echo intval($row["COMPLETED_QTY"]);?> / <?php echo intval($row["CALC_END_QTY"]);?> (<?php echo intval($row["PREV_OP_COMPLETED_QTY"]);?>) Stuks
<div class="tooltip12"><i class="fa fa-question-circle"></i>
<span class="tooltip12text">Aantal gereed / Totaal (Beschikbaar)</span>
</div><br>
Volgende bewerking: <?php echo $row["NEXT_OP"];?><br>
</div>
<div class="col-lg-1">
<?php if (transactionCodeDirect($Employee, $row["WORKORDER_BASE_ID"], $row["WORKORDER_LOT_ID"], $row["WORKORDER_SPLIT_ID"], $row["WORKORDER_SUB_ID"], $row["SEQUENCE_NO"], $row["RESOURCE_ID"]) <> ""){ ?>
<i class="fa fa-rotate-right fa-4x" text-center"></i><br><b>Running</b>
<?php } ?>
</div>
</div>
</div>
</a>
<?php
$i++;
}
}else{
echo "Result is niet groter dan 1";
}
It could be like this way.
foreach($_POST as $value){
if(is_array($value)){
foreach($value as $key => $val){
// first iteration
echo $key; // prio
echo $val; // 1
// in second iteration, `$val` contains '2'
}
}
}
Since you have two dimensional array, you can use foreach function in PHP to loop over the array. In the below code, I used nested foreach function to loop over two dimensional array.
echo "<table><tr>th>Key</th><th>Value</th></tr>";
foreach($_POST['your_array'] as $value){
if(is_array($value)){
foreach($value as $key => $val){
echo "<tr>";
echo "<td>" . $key . "</td>"; // prio
echo "<td>" . $val . "</td>"; // 1
echo "</tr>"
}
}
}
echo "</table>";
Related
I'm a new with PHP Array and have a form that input multiple parent-child data and save into an array. HTML will be something like this:
<ul>
<li><input type="text" name="group[0][name]" placeholder="Group name">
<ul>
<li>
<p>Member #1</p>
<input type="text" name="group[0][member][0][name]" placeholder="Name">
<input type="text" name="group[0][member][0][age]" placeholder="Age">
</li>
<li>
<p>Member #2</p>
<input type="text" name="group[0][member][1][name]" placeholder="Name">
<input type="text" name="group[0][member][1][age]" placeholder="Age">
</li>
</ul>
</li>
<li><input type="text" name="group[1][name]" placeholder="Group name">
<ul>
<li>
<p>Member #1</p>
<input type="text" name="group[1][member][0][name]" placeholder="Name">
<input type="text" name="group[1][member][0][age]" placeholder="Age">
</li>
</ul>
</li>
</ul>
PHP code:
$output = array();
$i = 0;
foreach ( $_POST['group'] as $group ) {
$members = array();
$m = 0;
foreach ( $_POST['group'][$i]['member'] as $name ) {
$members[$i][] = array(
'name' => $name,
'age' => $_POST['group'][$i]['member'][$m]
);
$m++;
}
$output[] = array(
'group_name' => $_POST['group'][$i]['name'],
'members' => $members[$i]
);
$i++;
}
var_dump( $output );
And I got this result:
array (size=2)
0 =>
array (size=2)
'group_name' => string 'Group 1' (length=7)
'members' =>
array (size=2)
0 =>
array (size=2)
...
1 =>
array (size=2)
...
1 =>
array (size=2)
'group_name' => string 'Group 2' (length=7)
'members' =>
array (size=1)
0 =>
array (size=2)
...
Can't get the member names and ages to be submitted into array. Can somebody help me? And sorry if I didn't explain this correctly. Thanks!
You have to process down the heirarchy, using the new arrays created by the foreach loop is also easier to understand than going back to the master array like you woudl have to in a for loop
$output = [];
foreach ( $_POST['group'] as $group ) {
$mem = []; // init the members each time you start a new group
foreach ( $group['member'] as $member) {
$mem[] = ['name' => $member['name'], 'age' => $member['age']];
}
$output[] = [ 'group_name' => $group, 'members' => $mem ];
}
I've a custom system that provides adding new information in custom columns.
I've two tables in my database. One for my value data and the second for the columns (data fieds).
Above you see a image from my form that is build by custom data fields with data per field.
Only in my for each i get for every data a extra loop so that is why i got from every data field two. How can I fix this?
<?php foreach ($list as $key => $value) { ?>
<?php foreach ($dataList as $data) { ?>
<div class="row clearfix">
<div class="col-xl-12">
<div class="form-group form-group-default">
<label><?php echo ucfirst($key); ?></label>
<?php if($key == $data['name']) { ?>
<input type="text" class="form-control" name="value_<?php echo trim($data['name']); ?>" value="<?php echo trim($data['value']); ?>" required>
<?php }else{ ?>
<input type="text" class="form-control" name="value_<?php echo trim($data['name']); ?>" placeholder="<?php echo ucfirst($key); ?>">
<?php } ?>
</div>
</div>
</div>
<?php } ?>
<?php } ?>
$list you'll find a list of data fields and in $dataList you'll find records of data.
Database structure:
data:
['id','hash','field_id','value']
Example of data:
['id' => 1, 'hash' => 123, 'field_id' => 1, 'value' => 'food']
Fields:
['id','name']
Example of fields:
['id' => 1, 'name' => 'firstname']
Below you'll find the foreach variables:
$data = processing('read', 'data JOIN fields ON data.field_id = fields.id', ['data.value,data.uid,fields.name,data.id,fields.category_id'], 'uid = "' . trim($_GET['datalist']) . '"', true);
$dataItem = processing('read', 'data JOIN fields ON data.field_id = fields.id', ['fields.category_id'], 'uid = "' . trim($_GET['datalist']) . '"');
$fieldList = processing('read', 'fields', ['name'], 'category_id = "'. trim($dataItem['category_id']) . '"',true);
$list = [];
foreach($fieldList as $key => $value) {
$list[$value['name']] = $value['name'];
}
Update:
I've update my own question because the other answers didn't resolved my problem. The only problem on my answer is, that when I update it doesnt look at the id of the item but at the name, so i can't save two items with the same name.
<?php foreach ($dataItems as $key => $value) { ?>
<div class="row clearfix">
<div class="col-xl-12">
<div class="form-group form-group-default">
<label><?php echo ucfirst($key); ?></label>
<input type="text" placeholder="<?php echo ucfirst($key); ?>" class="form-control" name="<?php echo trim($key); ?>" value="<?php echo trim($value); ?>">
</div>
</div>
</div>
<?php } ?>
method:
public function getDataListItems(int $category, array $list) {
global $dbh;
$query = 'SELECT data.value, data.uid, fields.name FROM data JOIN fields ON data.field_id = fields.id WHERE fields.category_id = "' . trim($category) . '" ORDER BY uid';
$sql = $dbh->prepare($query);
$sql->execute();
$values = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach ($values as $row) {
if (!isset($items[$row['uid']])) {
$items[$row['uid']] = array_fill_keys($list, ''); // if it needs to dynamically generated
$items[$row['uid']]['uid'] = $row['uid'];
}
$items[$row['uid']][$row['name']] = $row['value'];
}
return $items;
}
Return:
array (
'7d1f4f8e906245f' =>
array (
'Voornaam' => 'Bettina',
'Achternaam' => 'Les',
'Initialen' => 'pop',
'uid' => '7d1f4f8e906245f',
),
'7d1f4f8e906245g' =>
array (
'Voornaam' => 'Simone',
'Achternaam' => '',
'Initialen' => '',
'uid' => '7d1f4f8e906245g',
),
'7d1f4f8e906245l' =>
array (
'Voornaam' => 'test',
'Achternaam' => 'Kül',
'Initialen' => 'lol',
'uid' => '7d1f4f8e906245l',
),
'7d1f4f8e906245s' =>
array (
'Voornaam' => 'Joshua',
'Achternaam' => 'Mas',
'Initialen' => '',
'uid' => '7d1f4f8e906245s',
),
'gGcYEJdRYJ1vqcn' =>
array (
'Voornaam' => '',
'Achternaam' => 'Hello',
'Initialen' => '',
'uid' => 'gGcYEJdRYJ1vqcn',
),
)
I have this form with a bunch of sections, and some of them have name of an array because they are supposed to add up dynamically. I'm trying to perform htmlspecialchars on them first and then once the submit button is clicked, echo them out on a next confirmation page, but it won't work for some reason. I did print_r on $clean, but it didn't show the input $value of them, so I don't know where I did something wrong.
It would be great if somebody could help me on this.
Thank you.
Here is a part of the htmlspecialchars code.
$clean = array();
if( !empty($_POST) ) {
foreach( $_POST as $key => $value ) {
if( is_array($key)){
foreach($key as $key2 => $value2)
$clean[$key2] = htmlspecialchars( $value2, ENT_QUOTES);
} else {
$clean[$key] = htmlspecialchars( $value, ENT_QUOTES);
}
}
}
This is a html part of it
<div class="seconf-h-form">
<label>Multiple</label>
<input type="radio" id="r2" name="team_select"
onchange="toggleFunc('ex_t_button');" value="Multiple"/>
</div>
<div class="element_wrap" id="box_2">
<input type="submit" name="add" id="add" value="add more">
<label>The name of your team</label>
<input type="text" name="ex_team_n[]" id="ex_team_n"/>
<select name="ex_amount[]">
<option value="">Select</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<div id="add_section"></div>
and this is the part where I echo them out
<div class="element_wrap">
<label>The name of your team</label>
<p><?php echo $clean['ex_team_n']; ?></p>
</div>
<div class="element_wrap">
<label>The number of your team</label>
<p><?php echo $clean['ex_amount']; ?></p>
</div>
<input type="hidden" name="amount" value="<?php if(
$clean['team_select'] === "Multiple"){echo $clean['ex_team_n'];} ?>">
<input type="hidden" name="amount" value="<?php if(
$clean['team_select'] === "Multiple"){echo $clean['ex_amount'];} ?>">
You can use array_walk_recursive() to escape all data inside an array:
// Sample data, you can use $_POST instead or any other array
$array = array(
[
'a_key' => '<b>html</b>',
'b_key' => 'another code',
'c_key' => array('<script>alert(\'Hello\');</script>', 'No code, no change'),
],
[
'd_key' => '<small>ssup</small>',
'e_key' => 'stack',
'f_key' => 'overflow',
],
);
// Function to escape the value, you must pass the item by reference using the & operator
function html_escape(&$item){
$item = htmlspecialchars($item, ENT_QUOTES);
}
// Dump data before escaping
var_dump($array);
// Walk recursively through the array and call our function
array_walk_recursive($array, 'html_escape');
// Dump data after escaping
var_dump($array);
The data dumped before escaping
array (size=2)
0 =>
array (size=3)
'a_key' => string '<b>html</b>' (length=11)
'b_key' => string 'another code' (length=46)
'c_key' =>
array (size=2)
0 => string '<script>alert('Hello');</script>' (length=32)
1 => string 'No code, no change' (length=18)
1 =>
array (size=3)
'd_key' => string '<small>ssup</small>' (length=19)
'e_key' => string 'stack' (length=5)
'f_key' => string 'overflow' (length=8)
The data dumped after escaping
array (size=2)
0 =>
array (size=3)
'a_key' => string '<b>html</b>' (length=23)
'b_key' => string '<a href="http://example.com/">another code</a>' (length=68)
'c_key' =>
array (size=2)
0 => string '<script>alert('Hello');</script>' (length=54)
1 => string 'No code, no change' (length=18)
1 =>
array (size=3)
'd_key' => string '<small>ssup</small>' (length=31)
'e_key' => string 'stack' (length=5)
'f_key' => string 'overflow' (length=8)
Documentation for array_walk_recursive()
You're not iterating over the right object and not creating the inner array.
Replace the lines:
if( is_array($key)){
foreach($key as $key2 => $value2)
$clean[$key2] = htmlspecialchars( $value2, ENT_QUOTES);
with
if( is_array($value)){
foreach($value as $key2 => $value2) {
if (!isset($clean[$key])) $clean[$key] = array();
$clean[$key][$key2] = htmlspecialchars( $value2, ENT_QUOTES);
}
And then it should work properly.
function sanitizeMyArray($array) {
array_walk_recursive($array, 'standard');
return $array;
}
function standard(&$item, $key) {
//You must return this to $item for it to work.
$item = htmlspecialchars($item, ENT_QUOTES);
return $item;
}
$results = sanitizeMyArray($array);
print_r($results)
So I have a class selected, which should only be active when you are on the page of the link you pressed, and I am trying to get it in the code with php and asking if the current page is equal to any of the links and the one link that is equal should get the class.
<?php if ($categories) { ?>
<div class="menu col-sm-5 noPadding">
<?php foreach ($categories as $category) {
$url = "http://$_SERVER[SERVER_NAME]$_SERVER[REQUEST_URI]";
$isIt = $category['href']; ?>
<?php if ($url == $isIt){ ?>
<a class="selected" href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?></a>
<?php } else { ?>
<?php echo $category['name']; ?>
<?php } ?>
<?php } ?>
</div>
<?php } ?>
This is all in opencart and I would like to continue using foreach instead of having to code every link in by itself.
I've tried echoing them out and I get exactly the same things written.
Ok so this is the output from var_dump($categories)
array (size=4)
'name' => string 'Desktops' (length=8)
'children' =>
array (size=0)
empty
'column' => string '1' (length=1)
'href' => string 'http://localhost/openC/index.php?route=product/category&path=20' (length=67)
1 =>
array (size=4)
'name' => string 'Components' (length=10)
'children' =>
array (size=0)
empty
'column' => string '1' (length=1)
'href' => string 'http://localhost/openC/index.php?route=product/category&path=25' (length=67)
2 =>
array (size=4)
'name' => string 'Cameras' (length=7)
'children' =>
array (size=0)
empty
'column' => string '1' (length=1)
'href' => string 'http://localhost/openC/index.php?route=product/category&path=33' (length=67)
3 =>
array (size=4)
'name' => string 'MP3 Players' (length=11)
'children' =>
array (size=0)
empty
'column' => string '4' (length=1)
'href' => string 'http://localhost/openC/index.php?route=product/category&path=34' (length=67)
Try this:
<?php if ($categories) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>
<div class="menu col-sm-5 noPadding">
<?php foreach ($categories as $category) { ?>
<?php if ($url == html_entity_decode($category['href'])){ ?>
<a class="selected" href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?></a>
<?php } else { ?>
<?php echo $category['name']; ?>
<?php } ?>
<?php } ?>
</div>
<?php } ?>
'products' =>
array
0 =>
array
'pid' => string '3' (length=1)
'name' => string '#122232' (length=7)
'information' => string 'DSDSD' (length=5)
'image_tumb' => string '1tumbc4ad490017dc211002cfef359204ca7e154467_VisualVoicemail_Android_original.jpg' (length=80)
'tag' => string 'Sepatu' (length=6)
'price' => string '12000000.00' (length=11)
1 =>
array
'pid' => string '4' (length=1)
'name' => string 'Jam Bagus' (length=9)
'information' => string 'DSDSD' (length=5)
'image_tumb' => string '1tumbc4ad490017dc211002cfef359204ca7e_48447427_diaspora_dandy_logo.jpg' (length=70)
'tag' => string 'Jam' (length=3)
'price' => string '12000.00' (length=8)
2 =>
array
'pid' => string '6' (length=1)
'name' => string '#122232' (length=7)
'information' => string 'awdwad' (length=6)
'image_tumb' => string '1tumbc4ad490017dc211002cfef359204ca7e10408_710.jpg' (length=50)
'tag' => string 'Sepatu' (length=6)
'price' => string '140000.00' (length=9)
unlimited.
how do i display them like
name
name
name
name
<hr/>
name
name
name
name
<hr/>
or insert a hr after 4 times fetching ( currently useing PDO fecthall and foreach ) ?
// displays name loops like "namenamenamenamenamenametounlimiteddata"
foreach ($db['products'] as $product) {
echo "<div id='product'>";
echo $db[product][name];
echo "</div>";
}
but still no clue of doing the above. my friends say to use % sign in php? is that the best way ? if it is please give me an example how do it the right way, if there is a better way please describe it.
Thanks for looking in.
Adam Ramadhan
$i = 1;
foreach ($db['products'] as $product) {
echo "<div id='product'>";
echo $db[product][name];
echo "</div>";
if ($i % 4 == 0)
echo "<hr>";
$i++;
}
You can do:
$i = 0;
foreach ($db['products'] as $product) {
if($i && $i%4 == 0) {
echo "<hr />";
}
// your existing echo here
$i ++;
}
See it
Your friend is right you need to use the % operator called as modulus operator which gives the reminder after division.
$i = 0;
foreach ($db['products'] as $product) {
if($i%4 == 0)
echo "<hr>";
echo "<div id='product'>";
echo $db[product][name];
echo "</div>";
$i++;
}
Use a counter variable $i and increment it each time and check if
$i%4 == 0
then echo hr
From your example, I think you meant the 5th one.
Try something along the line of:
for($i = 0; $i < 100; $i++) {
if($i && $i%5 == 0) {
// the fifth
}
}
ops it's suppose to be 1
$a=1;
foreach ($db['products'] as $product) {
echo "<div id='product'>";
echo $db[product][name];
echo "</div>";
if($a%4==0){
echo "<hr/>";
}
$a++;
}