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)
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 ];
}
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>";
I'm trying to escape values from a multidimensional array for my database class. The code I have currently:
// Function to escape array values
private function esc_sql_arr(array $to_esc) {
$clean_arr = array();
foreach($to_esc as $k => $v) {
if(is_array($to_esc[$k])) {
foreach($to_esc[$k] as $key => $val) {
$k = $this->_mysqli->real_escape_string($k);
$key = $this->_mysqli->real_escape_string($key);
$val = $this->_mysqli->real_escape_string($val);
$clean_arr[$k][$key] = $val;
}
} else {
$k = $this->_mysqli->real_escape_string($k);
$v = $this->_mysqli->real_escape_string($v);
$clean_arr[$k] = $v;
}
}
return $clean_arr;
}
I'm assuming the following input example (it should be 'where', I purposely changed it to test the above method):
$args = array(
"table" => "t'1",
"data" => array(
"c'sf4;(" => 'xdfbxdrf',
'c2' => "'t'est'",
'cs' => 'hey'
),
"whe're" => array(
'test' => 'test1'
)
);
var_dump:
array (size=3)
'table' => string 't\'1' (length=4)
'data' =>
array (size=3)
'c\'sf4;(' => string 'xdfbxdrf' (length=8)
'c2' => string '\'t\'est\'' (length=10)
'cs' => string 'hey' (length=3)
'whe\'re' =>
array (size=1)
'test' => string 'test1' (length=5)
The code works without any issue. However, is this the right way to escape a multidimensional array?
I believe I might not have to use this method since I use prepared statements. Any feedback on using this is welcome.
My DB returns an array of objects with arrays within.
Var_dump
array (size=2)
0 =>
object(stdClass)[22]
public 'customer_id' => string '10' (length=2)
public 'cart' => string 'a:1:{s:32:"f9bb1d342b1c2a0bfe982ef405369ec0";a:9:{s:5:"rowid";s:32:"f9bb1d342b1c2a0bfe982ef405369ec0";s:2:"id";s:9:"101_30524";s:3:"qty";s:1:"1";s:5:"price";s:5:"104.5";s:4:"name";s:13:"Business Card";s:5:"image";s:18:"business-cards.gif";s:4:"ship";a:3:{s:6:"Ground";d:9.730000000000000426325641456060111522674560546875;s:11:"2nd Day Air";d:18.53999999999999914734871708787977695465087890625;s:9:"Overnight";d:26.269999999999999573674358543939888477325439453125;}s:7:"options";a:2:{s:17:"Print Description";s:16'... (length=761)
public 'shipping_type' => string 'Ground' (length=6)
public 'shipping_cost' => string '9.73' (length=4)
public 'order_sub_total' => string '104.50' (length=6)
public 'order_total' => string '114.23' (length=6)
public 'id' => string '28' (length=2)
public 'timestamp' => string '2012-10-12 20:10:30' (length=19)
1 =>
object(stdClass)[23]
public 'customer_id' => string '10' (length=2)
public 'cart' => string 'a:2:{s:32:"22d2d3d8584f6e0819c4e46af4d2fda2";a:9:{s:5:"rowid";s:32:"22d2d3d8584f6e0819c4e46af4d2fda2";s:2:"id";s:9:"101_94980";s:3:"qty";s:1:"1";s:5:"price";s:2:"64";s:4:"name";s:13:"Business Card";s:5:"image";s:18:"business-cards.gif";s:4:"ship";a:3:{s:6:"Ground";d:9.730000000000000426325641456060111522674560546875;s:11:"2nd Day Air";d:18.53999999999999914734871708787977695465087890625;s:9:"Overnight";d:26.269999999999999573674358543939888477325439453125;}s:7:"options";a:2:{s:17:"Print Description";s:164:"'... (length=1506)
public 'shipping_type' => string 'Ground' (length=6)
public 'shipping_cost' => string '19.46' (length=5)
public 'order_sub_total' => string '148.25' (length=6)
public 'order_total' => string '167.71' (length=6)
public 'id' => string '29' (length=2)
public 'timestamp' => string '2012-10-12 20:29:10' (length=19)
Notice cart is a multidimensional array. How do I loop through these objects and arrays and create a table?
<?php foreach($all_orders as $key => $val) : ?>
<?php echo $key; ?> <?php echo $val; ?>
<?php endforeach; ?>
This causes the following error: A PHP Error was encountered Severity: 4096 Message: Object of class stdClass could not be converted to string
Access the properties of the stdClass object using the -> operator:
<?php foreach($all_orders as $key => $val) : ?>
Customer ID <?php echo $val->customer_id ?> has a total of <?php echo $val->order_total ?><br />
<?php endforeach ?>
You can try
echo "<pre>";
foreach ( $cart as $all_orders ) {
foreach ( $all_orders as $key => $value ) {
echo $key, " = ", $value, PHP_EOL;
}
}
PHP 5 allows one to iterate over an object's public properties using a foreach loop.
For more information (and code examples): http://php.net/manual/en/language.oop5.iterations.php
I use PHP's ArrayObject in my MVC:
us3.php.net/manual/en/class.arrayobject.php
$arrayobject = new ArrayObject($dataRows);
for ($iterator = $arrayobject->getIterator(); $iterator->valid(); $iterator->next()) {
}
I'd like to take an array with this structure:
array
'Alabama' =>
array
0 =>
array
'id' => string '11' (length=2)
'region_name' => string 'Alabama' (length=7)
'city' => string 'Birmingham' (length=10)
1 =>
array
'id' => string '12' (length=2)
'region_name' => string 'Alabama' (length=7)
'city' => string 'Huntsville' (length=10)
2 =>
array
'id' => string '13' (length=2)
'region_name' => string 'Alabama' (length=7)
'city' => string 'Mobile' (length=6)
3 =>
array
'id' => string '14' (length=2)
'region_name' => string 'Alabama' (length=7)
'city' => string 'Montgomery' (length=10)
'Alaska' =>
array
0 =>
array
'id' => string '15' (length=2)
'region_name' => string 'Alaska' (length=6)
'city' => string 'Anchorage' (length=9)
And create unordered lists in html, like so:
<ul id="A">
<li class="state">Alabama</li>
<li>Birmingham</li>
<li>Huntsville</li>
<li>Mobile</li>
<li>Montgomery</li>
<li class="state">Alaska</li>
<li>Anchorage</li>
</ul>
<ul id="C">
<li class="state">California</li>
<li>Bakersfield</li>
<li>Fresno</li>
<li>Los Angeles</li>
</ul>
<ul id="D">
<li class="state">DC</li>
<li>Washington</li>
</ul>
The idea is an alphabetically ordered and grouped series of unordered lists, which I can show and hide easily using javascript. That part is easy... This part, I'm lost.
I've tried a sort of nested foreach loop, but the framework I'm using refused to do it citing OutputEscaper errors, which I believe made sense - I really am not sure how to do this properly.
I'd appreciate any help!
edit: Here's how the array is initially formatted:
$this->cityGroups = array();
foreach($this->USCities as $city)
{
$this->cityGroups[$city['region_name']][] = $city;
}
This is simple and it doesn't need a framework. If you data was formatted as I mentioned in my comment...
$data = array('Alabama' => array('Birmingham', 'Huntsville', 'Mobile', 'Montgomery'),
'Alaska' => array('Anchorage'));
ksort($data);
$formatted = array();
foreach($data as $state => $cities) {
$formatted[$state{0}][$state] = $cities;
}
foreach($formatted as $letter => $states) {
echo '<ul id="'.$letter.'">';
foreach($states as $state => $cities) {
sort($cities);
echo '<li class="state">'.$state.'</li>'
foreach($cities as $city) {
echo '<li>'.$city.'</li>';
}
}
echo '</ul>';
}
This solution should achieve what you're looking for:
$lastLetter = "A";
print( '<ul id="A">' );
foreach( $myArray as $key => $array ){
if( strtoupper( substr( $key, 0, 1 ) ) != $lastLetter ){
print( '</ul>' );
$lastLetter = strtoupper( substr( $key, 0, 1 ) );
print( '<ul id="' . $lastLetter . '">' );
}
print( '<li class="state">' . $key . '</li>' );
foreach( $array as $subArr ){
print( '<li>' . $subArr['city'] . '</li>' );
}
}
print( '</ul>' );
If you need an explanation on any specific part, please let me know.
Alternate Solution, in the event your starting letter is variable (may or may not be A)
Change:
$lastLetter = "A";
print( '<ul id="A">' );
to:
$temp = array_keys( $myArray );
$lastLetter = strtoupper( substr( $temp[0], 0, 1 ) );
print( '<ul id="' . $lastLetter . '">' );