Using foreach in a while statement - php

I am not sure if this is possible since I do not have much experience with foreach statements, but this is what I have
<?php $string = file_get_contents('data.xml') ?>
<?php
include("../connect.php");
$xml = new SimpleXMLElement($string);
//Loop trough multiple products
print "<table border='1' bordercolor='#6600FF' style='width='100%' cellpadding='3' cellspacing='3'>
<th>Campaign Name</th><th>Countries</th><th>Rate</th><th>Cash</th><th>Points</th>";
$cats = mysql_query("SELECT * FROM `offer_cats`");
while ($off = mysql_fetch_array($cats)) {
$cnames = array($off['name']);
$cnamess = implode(",", $cnames);
$cname = explode(",", $cnamess);
print_r($cnames);
foreach ($cnames as $category) {
$cat = $category;
}
}
foreach($xml->item as $item) {
$count = count(explode(", ",$item->countries));
if ($count >= 5) {
$country = "ALL INTL";
} else {
$country = $item->countries;
}
$rate = number_format((float)$item->rate, 2, '.', '');
$crates = $rate * 0;
$prates = $rate * 45;
$crate = number_format((float)$crates, 2, '.', '');
$prate = number_format((float)$prates, 2, '.', '');
echo'<tr><td>'.$item->name.'<br /><font color="limegreen" size="2">Incent: '.$item->incent.'</font><br /><select name="req" style="width:200px"><option value ="'.$item->requirements.'">'.$item->requirements.'</option></select>
<select style="width:200px" name="cat" id="cat"><option value="'.$cat.'">'.$cat.'</option></select><input type="button" name="add" value="+" /></td>';
echo '<td>'.$country.'</td>';
echo '<td>'.$item->rate.'</td>';
echo '<td><input type = "text" name="cash" value="'.$crate.'" style = "width:75px" /></td>';
echo '<td><input type = "text" name="points" value="'.$prate.'" style = "width:75px" /></td>';
// echo $item->incent;
// echo '<br/>';
}
?>
</tr>
</table>
I am trying to load all of the categories in this line <select style="width:200px" name="cat" id="cat"><option value="'.$cat.'">'.$cat.'</option></select> but it always loads only the last category in the array. Although I am pretty sure that the implode and explodes aren't really needed, it was an attempt to fix the error, but it was in vain. What exactly am I doing wrong?

Your first loop essentially just keeps overwriting the $cat variable:
foreach($cnames as $category){
$cat = $category;
}
You need to put this loop instead down where you want to loop through and output the options, like
echo '<select style="width:200px" name="cat" id="cat">';
foreach($cnames as $category){
echo '<option value="'.$cat.'">'.$cat.'</option>';
}
echo '</select>';

Related

Selecting specific id in foreach loop

$result = mysql_query("SELECT * FROM marias_products WHERE product_id = $id ");
$projects = array();
while($rowrow = mysql_fetch_assoc($result)){
$projects[] = $rowrow;
}
foreach ($projects as $project) {
$resultq = mysql_query("SELECT * FROM inventory WHERE product_id LIKE '%".$id."%'");
while($rows = mysql_fetch_array($resultq))
{
$qwerty=$rows['qtyleft'];
}
if ($qwerty!=0)
{
// echo '<input type="text" name="pizasize" value="'.$project['product_size_name'].'"/>';
echo '<input hidden type="text" name="idd" value="'.$project['mp_id'].'"/>';
echo '<tr>';
echo '<td>'.$project['product_size_name'].'</td>';
echo '<td>'.$project['product_price'].'</td>';
echo '<td>'.$project['mp_id'].'</td>';
echo '<td>'.'<input name="but" type="image" value="'.$project['mp_id'].'" src="images/button.png" />'.'</td>';
echo '</tr>';
}
else
{
echo 'not available';
}
}
I'm having a problem with getting the selected 'mp_id' inside in foreach loop. What happen is that once I select by clicking the button. I've selected the last ID of the entire table. Hope someone could help. Ty. Just learning PHP.

How to use condition within input tag using php?

If specific condition is true make input field readonly.
$todayDate = date('Y-m-d');
Here is the condition
$row["date"] == $todayDate (make input readonly true otherwise false)
while($row = $result->fetch_assoc()) {
$output .= '
<tbody><tr>
<td>'.$row["date"].'</td>
<td><input type="text" value = "'.$row["actual_closing_balance"].'"></td>
</tr>
</tbody>';
}
I would do it this way:
[ ... OTHER HTML ...]
<table>
<thead>
<tr><th>Date</th><th>Actual closing balance</th></tr>
</thead>
<?php
$todayDate = date('Y-m-d');
$output = "<tbody>\n";
while($row = $result->fetch_assoc())
{
$readonly = '';
if ($row['date'] == "$todayDate")
{
$readonly = 'readonly="readonly"';
}
$output .= " <tr><td>$row[date]</td><td><input type=\"text\" $readonly value=\"$row[actual_closing_balance].\"></td></tr>\n";
}
$output .= "</tbody>\n";
print $output;
?>
</table>
[...OTHER HTML...]
This way you have a properly formatted table (<tbody> tags appear only once). And you verify each row for the readonly attribute.
Do this:
$readonly = '';
if($row['date'] == $todayDate){
$readonly = 'readonly';
}
'<input type="text" value = "'.$row["actual_closing_balance"].' '.$readonly.' />';

Foreach php function inside HTML select options

Im a newbie to this forum and have just started coding in php. Need some help. I have the following code
<?php error_reporting(-1);
require_once('/mysql/sql_connect.php');
$q = "SELECT pty.pty_profile_name AS profile FROM pty, users WHERE users.username = 'testaccount' ";
$r = #mysqli_query ($dbc, $q);
$results_array = array();
while($row = mysqli_fetch_assoc($r)) {
array_push($results_array, $row);
echo "<pre>"; print_r($results_array); echo "</pre>"; }
?>
<p>
<form method="post" action="foreach2.php">
<label for="Property Select" class="title">Select Property</label>
<select name="pty_select" >
<?php foreach($results_array as $key => $value){ ?>
<option value="<?php echo $key; ?>"><?php echo $value['profile']; ?></option>
<?php } ?>
</select>
<input type="submit" name="Submit" />
</form>
<?php
if (isset($_POST['Submit'])) {
echo "<pre>"; echo ($_POST['pty_select']); echo "</pre>"; } ?>
The output I get is correct, but it displays the key, eg, 0 or 1 or 2, based on what I select in the form. I need the value output. Eg 0 = Emerton, it outputs "0" instead of Emerton.
If I echo $value['profile'] instead of pty_select, I get the last result of the query all the time. Which in this example would be 2, which is Ambarvale as I believe it just chooses the last row output of the query.
I hope I've made sense. Thanks in advance.
It will obviously echo the key, as you assigned the value of options as $key
if you need the options in the $_POST['pty_select'] use this:
<select name="pty_select" >
<?php foreach($results_array as $key => $value){ ?>
<option value="<?php echo $value['profile'];?>"><?php echo $value['profile']; ?></option>
<?php } ?>
</select>
You mean you need the value what you have used to display it.
Then,
Change to :
<option value="<?php echo $value['profile']; ?>">
<?php echo $value['profile']; ?>
</option>
And now let's go to ideal world :)
Build data pairs database_id => name for options:
$q = "SELECT pty.id, pty.pty_profile_name AS profile FROM pty, users
WHERE users.username = 'testaccount'";
$r = mysqli_query($dbc, $q);
$values = array();
while($r = mysqli_fetch_row($r)) {
$values[$r[0]] = $r[1];
}
Never use # when working with database, why do you want to suppress errors instead of preventing/handling them?
Now you have real database IDs and respective values (in general, using unique IDs are better... if nothing else they have greater entropy - more efficient search). And sice displaying select box is really common in webs, lets:
function selectbox( $values = array(), $attributes = array(), $selected_value = null)
{
// Header
echo '<select';
foreach( $attributes as $key => $val){
echo ' ' . htmlspecialchars($key) . '="' . htmlspecialchars( $val) . '"';
}
echo '>';
// Values
foreach( $values as $key => $val){
echo '<option value="' . htmlspecialchars( $key) .'"';
if( $key === $selected_value){
echo ' selected="selected"';
}
echo '>' . htmlspecialchars( $val) . '</option>';
}
echo '</select>';
}
And now usage :)
<form method="post" action="foreach2.php">
<label for="Property Select" class="title">Select Property</label>
<?php selectbox( $values, array( 'name' => 'pty_select')); ?>
<input type="submit" name="Submit" />
</form>
And what to do with it then?
$id = (int)(isset( $_POST['pty_select']) ? $_POST['pty_select'] : 0);
$name = null;
if( $id && isset( $values[$id])){
$name = $values[$id];
}
Give
<option value="<?php echo $value['profile']; ?>"><?php echo $value['profile']; ?></option>
instead of
<option value="<?php echo $key; ?>"><?php echo $value['profile']; ?></option>
if (isset($_POST['Submit'])) {
echo "<pre>"; echo ($_POST['pty_select']); echo "</pre>"; } ?>
Change it to something like
if(isset($_POST['Submit'])) {
echo $results_array[$_POST['pty_select']]['profile'];
}
Or alternatively use profile option value.

INSERT a row per array object

I am in the process of creating a document association tool whereby users can associate documents to a ticket from a pre-existing list of documents.
Thanks to the help of Alberto Ponte I was able to construct the initial radio box system (originally checkbox, changed for obvious reasons) from this question: Separate out array based on array data
Now that I have the radio buttons presenting correctly I am trying to get the data inserted into a MySQL with a row for each document. Following on from this I want to have it look up the table for each object and see if there is an existing entry and update that rather than inset a duplicate entry.
Apologies in advance for the soon to be depreciated code and I will be correcting the code going forward, however that is a much bigger task than I currently have time for.
Also apologies if the code is considered messy. I'm not fantastic at PHP and not too hot on best practices. Any quick pointers are always welcome.
Display code:
<?php
include "../includes/auth.php";
include "../includes/header.php";
## Security ########################################################
if ($company_id != 1 OR $gid < 7) {
echo' <div class="pageheader">
<div class="holder">
<br /><h1>Access Denied <small> Your attempt has been logged</small></h1>
</div>
</div>
';
exit();
}
// GET Values ###################################################
$jat_id = intval($_GET['id']);
$div_id = intval($_GET['div_id']);
## Page Start ########################################################
echo '
<div class="pageheader">
<div class="holder">
<br /><h1>Clovemead Job Management Platform<small> Welcome...</small></h1>
</div>
</div>
<div class="well5" style="width:1000px !important;">
<h3>Create Document Association</h3>
<table border=1>
<tr>
<td align=center><p>Here you can associate documents to Jobs and Tasks to.</p> </td>
</tr>
</table>';
$order2 = "SELECT * FROM documents";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
}
echo '
<h3>Documents</h3>
<table border=1>
<tr><th>Document Name</th><th>Document Type</th><th>Required</th><th>Optional</th><th>Not Required</th></tr>
';
$order2 = "SELECT * FROM documents ORDER BY type_id";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
$doc_type_id = $row2['type_id'];
echo '
<tr>
<td>'.$nice_name.'</td>';
$order3 = "SELECT * FROM document_types WHERE id = '$doc_type_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type_name = $row3['type_name'];
echo '
<td>'.$type_name.'</td>
<form method="post" action="create-doc-assoc-exec.php">
<input type="hidden" value="'.$doc_id.'" name="doc_id">
<input type="hidden" value="'.$jat_id.'" name="jat_id">
<input type="hidden" value="'.$div_id.'" name="div_id">';
$order4 = "SELECT * FROM document_assoc WHERE doc_id = '$doc_id'";
$result400 = mysql_query($order4);
$_results = mysql_fetch_array($result400);
if (!$_results) {
echo '
<td><input type="radio" name="req0" value="2"></td>
<td><input type="radio" name="req0" value="1"></td>
<td><input type="radio" name="req0" value="0" checked ></td>';
} else {
foreach ($_results as $result400) {
$requirement = $_results['requirement'];
}
$name = "req".$doc_id;
echo '
<input type="hidden" value ="'.$name.'" name="name">
<td><input type="radio" name="'.$name.'" value="2" '; if ($requirement == 2) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="1" '; if ($requirement == 1) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="0" '; if ($requirement < 1) { echo ' checked '; } echo '></td>';
}
}
echo '
</tr>';
}
echo '
</table>
<input type="submit" name="submit value" value="Create Document Association" class="btn success Large"></form>';
$order2 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$dbname = $row2['division_dbname'];
$order3 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type = $row3['type'];
$type2 = strtolower($type);
echo '
<input type="button" value="Back" onclick="window.location='./view-'.$type2.'.php?id='.$jat_id.''" class="btn primary Large">
';
}}
echo '
</div>';
include "../includes/footer.php";
?>
Execute Code:
<?php
include "../includes/dbconnect.php";
$name = $_POST['name'];
$name = stripslashes($name);
$name = mysql_real_escape_string($name);
$doc_id = intval($_POST['doc_id']);
$jat_id = intval($_POST['jat_id']);
$div_id = intval($_POST['div_id']);
$req = intval($_POST[$name]);
$req_blank = intval($_POST['req0']);
if ($req_blank == 0) {
$requirement = 0;
} elseif ($req_blank == 1) {
$requirement = 1;
} elseif ($req_blank == 2) {
$requirement = 2;
} elseif ($req == 0) {
$requirement = 0;
} elseif ($req == 1) {
$requirement = 1;
} elseif ($req == 2) {
$requirement = 2;
}
foreach ($doc_id as $doc_id2) {
$order = "INSERT INTO document_assoc (jat_id, dept_id, doc_id, requirement) VALUES ('$jat_id', '$div_id', '$doc_id2', '$requirement')";
$result = mysql_query($order);
$order1 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result1 = mysql_query($order1);
while ($row1 = mysql_fetch_array($result1)) {
$dbname = $row1['division_dbname'];
$order2 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$type = $row2['type'];
$type2 = strtolower($type);
if($result){
header("location:view-$type2.php?id=$jat_id&creation=success");
} else {
header("location:view-$type2.php?id=$jat_id&creation=failed");
}
}}
}
?>
A few reference points:
$doc_id is the ID of each document which is to be passed over as an array for use in a (i believe) foreach insert
$jat_id is the ticket id documents are being associated to
$div_id is the department the ticket is associated
And the radio boxes are to decider the requirement of each document. To be passed over inline with $doc_id
What I have tried:
After a fair bit of searching - finding nothing - rechecking my terminology and searching again I managed to find the suggestion of using base64_encode(serialize()) on the arrays but I could not get this to work.

Output a php multi-dimensional array to a html table

I have a form that has 8 columns and a variable number of rows which I need to email to the client in a nicely formatted email. The form submits the needed fields as a multidimensional array. Rough example is below:
<input name="order[0][topdiameter]" type="text" id="topdiameter0" value="1" size="5" />
<input name="order[0][bottomdiameter]" type="text" id="bottomdiameter0" value="1" size="5" />
<input name="order[0][slantheight]" type="text" id="slantheight0" value="1" size="5" />
<select name="order[0][fittertype]" id="fittertype0">
<option value="harp">Harp</option>
<option value="euro">Euro</option>
<option value="bulbclip">Regular</option>
</select>
<input name="order[0][washerdrop]" type="text" id="washerdrop0" value="1" size="5" />
<select name="order[0][fabrictype]" id="fabrictype">
<option value="linen">Linen</option>
<option value="pleated">Pleated</option>
</select>
<select name="order[0][colours]" id="colours0">
<option value="beige">Beige</option>
<option value="white">White</option>
<option value="eggshell">Eggshell</option>
<option value="parchment">Parchment</option>
</select>
<input name="order[0][quantity]" type="text" id="quantity0" value="1" size="5" />
This form is formatted in a table, and rows can be added to it dynamically. What I've been unable to do is get a properly formatted table out of the array.
This is what I'm using now (grabbed from the net).
<?php
if (isset($_POST["submit"])) {
$arr= $_POST['order']
echo '<table>';
foreach($arr as $arrs)
{
echo '<tr>';
foreach($arrs as $item)
{
echo "<td>$item</td>";
}
echo '</tr>';
}
echo '</table>;
};
?>
This works perfectly for a single row of data. If I try submitting 2 or more rows from the form then one of the columns disappears. I'd like the table to be formatted as:
| top | Bottom | Slant | Fitter | Washer | Fabric | Colours | Quantity |
------------------------------------------------------------------------
|value| value | value | value | value | value | value | value |
with additional rows as needed. But, I can't find any examples that will generate that type of table!
It seems like this should be something fairly straightforward, but I just can't locate an example that works the way I need it too.
How about this?
$keys = array_keys($_POST['order'][0]);
echo "<table><tr><th>".implode("</th><th>", $keys)."</th></tr>";
foreach ($_POST['order'] as $order) {
if (!is_array($order))
continue;
echo "<tr><td>".implode("</td><td>", $order )."</td></tr>";
}
echo "</table>
A Table class I wrote some time ago
<?php
class Table {
protected $opentable = "\n<table cellspacing=\"0\" cellpadding=\"0\">\n";
protected $closetable = "</table>\n";
protected $openrow = "\t<tr>\n";
protected $closerow = "\t</tr>\n";
function __construct($data) {
$this->string = $this->opentable;
foreach ($data as $row) {
$this->string .= $this->buildrow($row);
}
$this->string .= $this->closetable;
}
function addfield($field, $style = "null") {
if ($style == "null") {
$html = "\t\t<td>" . $field . "</td>\n";
} else {
$html = "\t\t<td class=\"" . $style . "\">" . $field . "</td>\n";
}
return $html;
}
function buildrow($row) {
$html .= $this->openrow;
foreach ($row as $field) {
$html .= $this->addfield($field);
}
$html .= $this->closerow;
return $html;
}
function draw() {
echo $this->string;
}
}
?>
To be used like this :
<body>
<?php
$multiDimArray = []; # Turn the form array into a matrix
for ($i = 0; $i < count($_POST['order']); $i++) {
$multiDimArray[] = [];
foreach ($_POST['order'][$i] as $key=>$value) {
if ($i == 0) {
$multiDimArray[$i][] = $key;
}
$multiDimArray[$i][] = $value;
}
}
$table = new Table($multiDimArray); # Create and draw the table
$table->draw();
?>
</body>
In your HTML, try something like this:
<table>
<tr>
<th>Bottom</th>
<th>Slant</th>
<th>Fitter</th>
</tr>
<?php foreach ($_POST['order'] as $order): ?>
<tr>
<td><?php echo $order['bottomdiameter'] ?></td>
<td><?php echo $order['slantheight'] ?></td>
<td><?php echo $order['fittertype'] ?></td>
</tr>
<?php endforeach; ?>
</table>
Obviously, I'm not including all your attributes there, but hopefully you get the idea.

Categories