PHP/MySQL: Show only specific columns within a loop? - php

I am programming a voting system where users can upload up to 20 images per project (see attached image). Currently I am displaying per Row the project ID, an image and a text (text is the same in the same project). When the user adds 20 Images to the project the text will be shown 20 times. Now I am trying to rebuild the display part (see the attached Image) - instead of 20 rows, there should only be one row per user and project, but I have no clue how to achieve this. Thank you for your help.
This is my SQL syntax:
SELECT * from wp_awa_upload WHERE wp_awa_upload.uid = '$_SESSION[id]' and stat < 3 order by parent_cat, id asc
And this is the Part where I print the result of the table:
<form method="POST" action="<?php echo $_SERVER["PHP_SELF"]; ?>" enctype="multipart/form-data">
<? $i = 0; ?>
<? while ($show = mysql_fetch_array($abfrage)) { ?>
<form action="" method="POST">
<td><? echo $show['parent_cat'];?><br><input name="uid" type="#hidden" class="style13" value="<?php echo $show['uid']; ?>" id="uid" style="width: 40px" readonly /></td>
<td align="center"><? echo $show['file_name']; ?><br><div class="center-cropped"><img src="<? echo $show['url'] ?>" border="0"><br></div><br>©: <input name="copyright" type="text" class="style13" value="<?php if ($rolle <> '1') {echo $show['copyright'];} ?>" id="copyright" style="width: 140px" /><br><? if ( $show['youtube'] <> '') { echo 'Youtube'; }?></td>
<td><textarea name ='project' rows='16' cols='30' style="resize: none;"><?php if ($i == 0) { echo $show['project']; } ?></textarea></td>
<td><textarea name ='testimonial' rows='16' cols='30' style="resize: none;"><?php echo $show['testimonial']; ?></textarea><br>
<? if ($show['parent_cat'] == "Bester Styled Shoot") { ?>Styled Shoot Teilnehmer<br>
<textarea name ='styled' rows='8' cols='30' style="resize: none;"><?php echo $show['styled']; } ?></textarea></td>
<td><textarea name ='beschreibung' rows='16' cols='30' style="resize: none;"><?php echo $show['beschreibung']; ?></textarea></td>
<td><? if ($rolle <> 1 && $show['stat'] == 0 ) { echo '<button type="submit" value="' . $show['id']. '" name="change">Speichern?</button>'; ?><br><? echo '<button type="submit" value="' . $show['id']. '" name="delete">Löschen?</button>'; } ?></td>
<td><? if ($rolle == '1') { ?>
<select name="rating" class="style28" style="width: 120px" id="rating">
<option value="0">0</option>
<option value="5">5</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
<option value="55">55</option>
<option value="60">60</option>
<option value="65">65</option>
<option value="70">70</option>
<option value="75">75</option>
<option value="80">80</option>
<option value="85">85</option>
<option value="90">90</option>
<option value="95">95</option>
<option value="100">100</option>
</select> <? echo '<button type="submit" value="' . $show['id']. '" name="submit">Bewerten?</button>'; }
elseif ($rolle == 9) {
echo '<button type="freigeben" value="' . $show['id']. '" name="freigeben">Freigeben?</button>';
echo '<button type="verwerfen" value="' . $show['id']. '" name="verwerfen">Verwerfen?</button><br><br>';
echo '<hr><br>'; ?>
E-Mail an Kunden schreiben:<br><textarea name ='informed' rows='8' cols='30' style="resize: none;"></textarea><br>
<? echo '<button type="informieren" value="' . $show['id']. '" name="informieren">Informieren?</button>';
}?></td>
</form>
I tried with an $i = 0; and then with a "if $i == 0 {} but, this is not working if a user has more than 1 project (the other project will not be displayed)
Thank you for your help!
Kind Regards, Stefan

I guess you want to display common text for all similar project images and id with It's related id & image.
You can do this by creating sub-array for managing image & id & main array for text description. Whenever same description received it'll break the loop & sub sequent data will be added as sub-array of main array. Try this. Hope it helps
$mainArry = array();
foreach($arrData as $item){
$idx = 0;
foreach($mainArry as $cat){
if($cat['text_description'] == $item['text_description']){
break;
}
$idx++;
}
$itemArry = array('id'=> ,'images' => );
if($idx >= 0){
$mainArry[$idx]['text_description'] = $item['text_description'];
$mainArry[$idx]['items'][] = $itemArry;
}
}

You should be doing a preprocessing of data (data massaging) before you use it for your template.
You can start by grouping rows with similar project
Example:
$processed_data = array();
foreach($rows as $row){
$processed_data[$row["project_id"][] = $row;
}
In this way, you can have something like this;
[
1 => [
[project 1, image1...]
[project 1, image2...]
[project 1, image3...]
],
2 => [
[project 2, image1...]
[project 2, image2...]
.....
]
]
Then in your template, it will be easier for you to display data with similar group

There are two methods I have mentioned below.
Please note that, these solutions are given based on following assumtions
1. You are using PHP
2. Database field names are userid, prjoject, text, image
3. You have stored imge src in the database.
Method 1:
SELECT userid, project,
GROUP_CONCAT(image separator ',') as images_list,
GROUP_CONCAT(image separator ',') as text_list
FROM your_table
GROUP BY userid,project
Above query returns data as you expected. Now you just need to populate those data into a html table.
Method 2:
Group data by user and project in your php code using a associative array.
$sql = "SELECT * FROM your_table";
Get query result to a PHP associative array. I assume the variable name is $data
$result = array();
foreach($data as $row) {
$userid = $row['userid'];
$project = $row['project'];
$result[$userid][$project]['text'][] = array('text' => $row['text'], 'image' => $row['image']);
}
HTML:
<table>
<?php foreach($result as $key_1 => $projects) { //userid holds $key_1 ?>
<?php foreach($projects as $key_2 => row ) {?>
<tr>
<td><?php echo $key_1; ?></td>
<td><?php echo $key_2; ?></td>
<td>
<table>
<tr><td><?php echo $row['text']?></td><tr>
<tr><td><img src="<?php echo $row['image']?>"></td><tr>
</table>
</td>
</tr>
<?php }?>
<?php } ?>
</table>
Following links may be helpful for more understanding.
MySql GROUP_CONCAT
PHP Associative array.

Hi thank you for your answers so far. I am nearly at the point where I could say "solved" :-)
$sql = "SELECT * from wp_awa_upload where stat = '0' order by parent_cat asc";
if (!$result = $mysqli->query($sql)) {
// Oh no! The query failed.
echo "Sorry, the website is experiencing problems.";
// Again, do not do this on a public site, but we'll show you how
// to get the error information
echo "Error: Our query failed to execute and here is why: \n";
echo "Query: " . $sql . "\n";
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
$last_entry = null;
echo "<table width='100%' border='1' align='center'><tr>";
echo "<tr>";
echo "<td align='center'>Projektnamen</td>";
echo "<td align='center'>UID</td>";
echo "<td align='center'>Kategorie</td>";
echo "<td align='center'>Projektbeschreibung</td>";
echo "<td align='center'>Beschreibung</td>";
echo "<td align='center'>Copyright</td>";
echo "<td align='center'>Tools</td>";
echo "</tr>";
while ($row = $result->fetch_object()) {
echo "<tr>";
if ($last_entry != $row->project) {
echo "<td align='center'><textarea name ='project' rows='16' cols='30' style='resize: none'>".$row->project."</textarea></td>";
echo "<td align='center'>".$row->uid."</td>";
echo "<td align='center'>".$row->parent_cat."</td>";
echo "<td align='center'><textarea name ='project_desc' rows='16' cols='30' style='resize: none'>".$row->project_desc."</textarea></td>";
echo "<td align='center'><textarea name ='beschreibung' rows='16' cols='30' style='resize: none'>".$row->beschreibung."</textarea></td>";
echo "<td align='center'>".$row->copyright."</td>";
echo "<td align='center'>Buttons</td>";
echo "</tr>";
echo "<tr>";
$last_entry = $row->project;
}
//echo "<td align='center' colspan='6'><img src=".$row->url."<border='0'> </td>";
echo "<td align='center' colspan='7'>";
echo "<a href='".$row->url."' data-lightbox='".$row->file_name."' data-title='".$row->file_name."'><br><div class='center-cropped'><img src='".$row->url."' border='0'></a></div>";
}
echo "</tr>";
echo "</table>";
The Description, Category,... will be displayed only once, the images will be displayed, but not side by side - they will be displayed with a line break.
My Question: How can I display the images side by side (4 in a row?) As I could have up to 20 Images in a project, it would be nice to show them in a pack of 4 and a max. of 5 Rows.
Thank you for you help and assistance.
Kind Regards,
Stefan

Related

Multiple Choice Quiz - not updating responses

I have a form that outputs:
Quiz_Assign_ID (Combines User_ID with Quiz ID)
Question ID
Checkboxes for inputting the response (Option A, Option B, Option C)
<div class="Main">
<form method="post" action="LP_Quiz_Student_Quiz_Responses.php">
<?php
$quiz_id = trim($_GET['quiz_id']);
$quiz_assign_id = trim($_GET['quiz_assign_id']);
$i = 1;
$count=1;
$sel_query=("SELECT Quiz.quiz_id, Quiz.quiz_title, Quiz_Questions.quiz_id, Quiz_Questions.quiz_question_id, Quiz_Questions.question, Quiz_Questions.option1, Quiz_Questions.option2, Quiz_Questions.option3, Quiz_Questions.answer FROM Quiz, Quiz_Questions WHERE (Quiz.quiz_id=Quiz_Questions.quiz_id) and (Quiz.quiz_id=?)");
$stmt = $conn->prepare($sel_query);
$stmt->bind_param("i", $quiz_id);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
if($result->num_rows === 0) exit('No Quiz Questions!');
while($row = $result->fetch_assoc()) { ?>
<p></p>
<p> </p>
<table>
<tr>
<td>
</td>
<td>
<input name="quiz_assign_id" type="hidden" value=" <?php echo $quiz_assign_id; ?>" /> <input name="quiz_question_id" type="hidden" value=" <?php echo $row["quiz_question_id"]; ?>" /></td>
<td> </td>
</tr>
<tr>
<td>
<h4>Question <?php echo $i++; ?> </h4>
</td>
<td>
<h4><?php echo $row["question"]; ?> </h4>
</td>
<td> </td>
</tr>
<tr>
<td>
<h4>A</h4>
</td>
<td><?php echo $row["option1"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option A" style="width: 20px" /></td>
</tr>
<tr>
<td>
<h4>B</h4>
</td>
<td><?php echo $row["option2"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option B" /></td>
</tr>
<tr>
<td>
<h4>C</h4>
</td>
<td><?php echo $row["option3"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option C" /></td>
</tr>
</table>
<?php
}
?>
<input name="Submit1" type="submit" value="submit" />
</form>
</div>
Upon submission I run the following script, which captures the response but does not get the question_id and Quiz_Assign_ID and does not update the values in the database:
<?php
if(!empty($_POST['Response'])) {
foreach ($_POST['Response'] as $value) {
$quiz_assign_id=trim($_POST['quiz_assign_id']);
$quiz_question_id=$_POST['quiz_question_id'];
echo 'Answer'; echo $value;
echo 'Question:'; echo $quiz_question_id;
echo 'Student ID'; echo $quiz_assign_id; echo 'successfully assigned! <br>';
$stmt = $conn -> prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
if (
$stmt &&
$stmt -> bind_param('sss', $value, $quiz_assign_id, $quiz_question_id) &&
$stmt -> execute() &&
$stmt -> affected_rows === 1
) {
echo "<script>
alert('Responses submitted!');
window.history.go(-2);
</script>";
} else {
echo"<script>
window.history.go(-2);
</script>";
}
}
}
?>
I have been playing with it for hours, but with no luck.
Because you are using check boxes en not radio buttons, you should change your input checkbox name attribute, so it's sending a nested array with the question ID as a key and the answers array as the value, like so: (notice the extra []) Also $quiz_question_id is not defined, you should use the $row array.
<input name="Response[<?php echo $row['quiz_question_id']; ?>][]" type="checkbox" value="Option A" style="width: 20px" /></td>
Because the response array is now nested, the question answers are grouped by question_id. To iterate over the nested response array, use the following for loop:
foreach ($_POST['Response'] as $question_id => $answered) {
echo "Question ID:".$question_id."<br />";
// iterate answers
foreach ($answered as $answer) {
echo "Answered: ".$answer."<br />";
}
// Or transform to comma separated string
echo "Answered: ".implode(", ", $answered)."<br />";
}
So your LP_Quiz_Student_Quiz_Responses.php could look like this:
if(!empty($_POST['Response'])) {
$done = 0;
foreach ($_POST['Response'] as $quiz_question_id => $values) {
$quiz_assign_id = trim($_POST['quiz_assign_id']);
echo 'Answers'; print_r($values); // Values is an array here.
echo 'Question:'; echo $quiz_question_id;
echo 'Student ID'; echo $quiz_assign_id; echo 'successfully assigned! <br>';
// Because $values is an array, transform it into a comma separated string to insert them into the database
// But you could also make a database table with answers and loop over the $values array.
$value = implode(', ', $values);
$stmt = $conn->prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
$stmt->bind_param('sss', $value, $quiz_assign_id, $quiz_question_id);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$done++;
}
}
echo "<script>";
if ($done) {
echo "alert('Responses submitted!');";
}
echo "window.history.go(-2);";
echo "</script>";
}
To accommodate both type of questions with check boxes and questions with radio buttons, you can use the same response code, but first check if its an array before transforming it into a string.
Questions with radio buttons, one answer per question possible:
<input name="Response[<?php echo $row['quiz_question_id']; ?>]" type="radio" value="Option A" style="width: 20px" /></td>
Questions with check boxes, multiple answers per question possible:
<input name="Response[<?php echo $row['quiz_question_id']; ?>][]" type="checkbox" value="Option A" style="width: 20px" /></td>
And now your LP_Quiz_Student_Quiz_Responses.php could look like this:
if(!empty($_POST['Response'])) {
$done = 0;
foreach ($_POST['Response'] as $quiz_question_id => $values) {
$quiz_assign_id = trim($_POST['quiz_assign_id']);
// If it's an array (checkbox), transform to string.
// Else it is already a string (radio).
if (is_array($values)) {
$values = implode(', ', $values);
}
$stmt = $conn->prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
$stmt->bind_param('sss', $values, $quiz_assign_id, $quiz_question_id);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$done++;
}
}
echo "<script>";
if ($done) {
echo "alert('".$done." Responses submitted!');";
}
echo "window.history.go(-2);";
echo "</script>";
}
But with above code you can accommodate all kind of field types.
To put it simple:
foreach ($_POST['Response'] as $question_id => $answered) {
echo "Question ID:".$question_id."<br />";
// Check if array, it's a checkbox or multiple select question
if (is_array($answered)) {
// iterate answers
foreach ($answered as $answer) {
echo "Answered: ".$answer."<br />";
}
// Or transform to comma separated string
echo "Answered: ".implode(", ", $answered)."<br />";
} else {
// radio, hidden, input, select or textarea question
echo "Answered: ".$answered."<br />";
}
}
I hope this points you in the right direction.

Wrong output with an addition table in php

I am having trouble creating an addition table for my php program. I created my multiplication table just fine (it creates the right output), but when I try and make an addition one the numbers arent inside the table and I cant figure out what I am doing wrong. I will post what my output looks like when I create an addition table, and what it is supposed to look like and also the code that I have wrote. I feel like I am very close to completing this program, but right now I am stuck, thanks for the help in advance.
Here is the output that I am supposed to get for a 4x5 addition table.
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
Here is my output .
11112222333344445555
0 1 2 3 4
1
2
3
4
5
And here is my code. Any help is appreciated.
<html>
<head/>
<body>
<form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>" >
<table border="1">
<tr><td>Number of Rows:</td><td><input type="text" name="rows" /></td></tr>
<tr><td>Number of Columns:</td><td><select name="columns">
<option value="1">1</option>
<option value="2">2</option>
<option value="4">4</option>
<option value="8">8</option>
<option value="16">16</option>
</select>
</td></tr>
<tr><td>Operation:</td><td><input type="radio" name="operation" value="multiplication" checked="yes">Multiplication</input><br/>
<input type="radio" name="operation" value="addition">Addition</input>
</td></tr>
</tr><td colspan="2" align="center"><input type="submit" name="submit" value="Generate" /></td></tr>
</table>
</form>
<?php
if(isset($_POST["submit"])){
//check to see if num of rows is numberic
if ( isset($_POST["rows"]) && is_numeric($_POST["rows"])){
//check to see if rows is a positive number
if($_POST["rows"] > 0){
if(isset($_POST) && $_POST["operation"] == "multiplication"){
echo 'This is a '. $_POST["rows"] . ' x ' . $_POST["columns"] .'multiplication table';
echo "<table border=1";
echo'<tr>';
for($b = 0; $b <= $_POST["columns"];$b++){
echo '<th>'.$b.'</th>';}
echo '</tr>';
for($r = 1; $r <= $_POST["rows"]; $r++){
echo'<tr><th>'.$r.'</th>';
for($c = 1; $c <= $_POST["columns"]; $c++){
echo '<td>' .$c*$r. '</td>';
}
echo '</tr>';
}
echo "</table>";
}
else if (isset($_POST) && $_POST["operation"] == "addition")
{
echo 'This is a '. $_POST["rows"]. ' x ' . $_POST["columns"] .' addition table';
echo "<table border = 1";
echo'<tr>';
for($a = 0; $a <= $_POST["columns"];$a++){
echo '<th>'.$a.'</th>';}
echo '</tr>';
for($r = 1; $r <= $_POST["rows"]; $r++){
echo '<tr><th>'.$r.'</th>';
for($c = 1; $c <= $_POST["columns"]; $c++)
{
echo '<td>' .$c+$r. '</td>';
}
echo '</tr>';
}
echo "</table>";
}
else{
echo 'Invalid rows columns parameters';
exit();
}
}
exit();
}}
?>
</body>
</html>
try this.
Note: i only changed elseif statement which you used for additioin, so you can just copy and paste this as i changes nothing else.
so i divided the solution in three part and leave comment in bold for you to know which part i changed. thanks.
and post the comment what should you do next. In case it did not give you desired out come.
<html>
<head/>
<body>
<form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>" >
<table border="1">
<tr><td>Number of Rows:</td><td><input type="text" name="rows" /></td></tr>
<tr><td>Number of Columns:</td><td><select name="columns">
<option value="1">1</option>
<option value="2">2</option>
<option value="4">4</option>
<option value="8">8</option>
<option value="16">16</option>
</select>
</td></tr>
<tr><td>Operation:</td><td><input type="radio" name="operation" value="multiplication" checked="yes">Multiplication</input><br/>
<input type="radio" name="operation" value="addition">Addition</input>
</td></tr>
</tr><td colspan="2" align="center"><input type="submit" name="submit" value="Generate" /></td></tr>
</table>
</form>
<?php
if(isset($_POST["submit"])){
//check to see if num of rows is numberic
if ( isset($_POST["rows"]) && is_numeric($_POST["rows"])){
//check to see if rows is a positive number
if($_POST["rows"] > 0){
if(isset($_POST) && $_POST["operation"] == "multiplication"){
echo 'This is a '. $_POST["rows"] . ' x ' . $_POST["columns"] .'multiplication table';
echo "<table border=1";
echo'<tr>';
for($b = 0; $b <= $_POST["columns"];$b++){
echo '<th>'.$b.'</th>';}
echo '</tr>';
for($r = 1; $r <= $_POST["rows"]; $r++){
echo'<tr><th>'.$r.'</th>';
// for($c = 1; $c <= $_POST["columns"]; $c++){
// echo '<td>' .$c*$r. '</td>';
//}
echo '</tr>';
}
echo "</table>";
}
From here i change the code In case it does not give you desired outcomes. you only have to change for loop part just change $_post['rows'] to $_post['columns'] in the first foreach loop. And in the second for loop chnage $_post['columns'] to $_post['rows']. Thanks
else if (isset($_POST) && $_POST["operation"] == "addition")
{
for($x=0; $x<$_POST['rows']+1; $x++)
{
$i=0;
$y= $i+$x;
echo '<table border 1px solid black>';
echo '<tr>';
//$value[]=$x;
echo '<td>'.$y.'</td>';
for($value=1;$value<$_POST['columns']+1;$value++){
$c=$y+$value;
// $c=$y+$value;
echo '<td>'.$c;
echo '</td>';
}
echo '</tr>';
echo '</table>';
}
My changes finished Every thing is your code as it is.
echo "</table>";
}
else{
echo 'Invalid rows columns parameters';
exit();
}
}
exit();
}}
?>
</body>
</html>
It is actually a simple bug!
There is no error in your logic. The bug is in your echo statement for addition.
You just can't echo the addition directly. Use a bracket to surround them instead. It will work :-)
Like this;
echo '<td>'.($c+$r).'</td>';
Please let us know if it solved your problem.
Thanks,

Having problems getting info from database

I'm receiving this error:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, string given in C:\wamp\www\dev\includes\class\class_db_mysql.php on line 67
Call Stack
# Time Memory Function Location
1 0.0030 343136 {main}( ) ..\edit.php:0
2 0.0103 437760 database->fetch_row( ) ..\edit.php:380
3 0.0103 437808 mysql_fetch_assoc ( ) ..\class_db_mysql.php:67
page code is:
<?php
require_once 'includes/header.php';
$_GET['edit'] = abs((int) $_GET['edit']);
function item_dropdown1($connection,$ddname="item1",$selected=-1)
{
global $db;
$ret="<select name='$ddname' type='dropdown'>";
$q=$db->query("SELECT * FROM stock ORDER BY name ASC");
if($selected < 1) { $ret.="<option value='0' selected='selected'>-- None --</option>"; }
else { $ret.="<option value='0'>-- None --</option>"; }
while($r1=$db->fetch_row($q))
{
$ret.="\n<option value='{$r1['id']}'";
if ($selected == $r1['id']) { $ret.=" selected='selected'";$first=1; }
$ret.=">{$r1['name']} For {$r1['cat']} > {$r1['subcat']}</option>";
}
$ret.="\n</select>";
return $ret;
}
$q1=$db->query("SELECT * FROM repairs WHERE r_id={$_GET['edit']}");
$selnotes=$db->query("SELECT * FROM notes WHERE linkedtoid={$_GET['edit']}");
$selparts=$db->query("SELECT * FROM usedparts WHERE binded_to={$_GET['edit']}");
$fq=$db->fetch_row($q1);
$fname = mysql_real_escape_string(strip_tags($_POST['first_name']));
$lname = mysql_real_escape_string(strip_tags($_POST['last_name']));
$email = mysql_real_escape_string(strip_tags($_POST['email']));
$cno = mysql_real_escape_string(strip_tags($_POST['contact_no']));
$fault = mysql_real_escape_string(strip_tags($_POST['fault']));
$make = mysql_real_escape_string(strip_tags($_POST['make']));
$device = mysql_real_escape_string(strip_tags($_POST['device']));
$model = mysql_real_escape_string(strip_tags($_POST['model']));
$price = mysql_real_escape_string(strip_tags($_POST['price']));
$notes = mysql_real_escape_string(strip_tags($_POST['notes']));
$status = mysql_real_escape_string(strip_tags($_POST['status']));
$posted = mysql_real_escape_string(strip_tags($_POST['posted']));
$partsfitted = $_POST['pf'];
if (isset($_POST['posted']) == 'TRUE') {
$db->query("UPDATE repairs SET r_oem='$make', r_device='$device', r_mod='$model', r_reserve='$fault', r_price='$price', r_notes='$notes', rc_fname='$fname', rc_lname='$lname', rc_email='$email', rc_contactno='$cno', rc_status='$status' WHERE r_id='{$_GET['edit']}'");
if ($partsfitted == 1) {
$db->query("UPDATE repairs SET rc_status=3 WHERE r_id='{$_GET['edit']}'");
if ($fq['part1id']) {
$item1=$fq['part1id'];
$db->query("UPDATE stock SET commited=commited-1, totalused=totalused+1 WHERE id='$item1'");
$db->query("UPDATE repairs SET part1id=0 WHERE r_id='{$_GET['edit']}' ");
}
if ($fq['part2id']) {
$item2=$fq['part2id'];
$db->query("UPDATE stock SET commited=commited-1, totalused=totalused+1 WHERE id='$item2'");
$db->query("UPDATE repairs SET part2id=0 WHERE r_id='{$_GET['edit']}' ");
}
if ($fq['part3id']) {
$item3=$fq['part1id'];
$db->query("UPDATE stock SET commited=commited-1, totalused=totalused+1 WHERE id='$item3'");
$db->query("UPDATE repairs SET part3id=0 WHERE r_id='{$_GET['edit']}' ");
}
if ($fq['part4id']) {
$item4=$fq['part1id'];
$db->query("UPDATE stock SET commited=commited-1, totalused=totalused+1 WHERE id='$item4'");
$db->query("UPDATE repairs SET part4id=0 WHERE r_id='{$_GET['edit']}' ");
}
if ($fq['part5id']) {
$item5=$fq['part1id'];
$db->query("UPDATE stock SET commited=commited-1, totalused=totalused+1 WHERE id='$item5'");
$db->query("UPDATE repairs SET part5id=0 WHERE r_id='{$_GET['edit']}' ");
}
else {print "This item has already been marked as repaired";}
}
echo '<font color="green">OK</font> : Successfully UPDATED ID'; PRINT " {$_GET['edit']} <b>";
echo '</b><br />';
}
if(!$_GET['edit'])
{
// no profile defined. give list of last 100 entries in table..
print "Click a listing below to edit it.";
$qresults=$db->query("SELECT * FROM repairs order by r_id DESC LIMIT 100");
print "<table border=\"1\" cellspacing=\"1\" width=\"80%\"><tr style='background:lightblue'><th colspan=\"6\"><h3>Last 100 entries in descending order.</h3></th></tr>";
echo '<tr class="bgalt5"><th>First Name</th><th>Last Name</th><th>Phone No</th><th>Device</th><th>status</th><th>Edit / Delete</th></tr>';
while($qr=$db->fetch_row($qresults))
{
if ($alternate % 2 == 0){
echo "<tr class='bgalt1'>";
}
else{
echo "<tr class='bgalt3'>";
}
print "
<td>{$qr['rc_fname']}</td>
<td>{$qr['rc_lname']}</td>
<td>{$qr['rc_contactno']}</td>
<td>{$qr['r_oem']} > {$qr['r_device']} > {$qr['r_mod']}</td>
<td>";
if ($qr['rc_status'] == 1) {echo 'Received';}
else if ($qr['rc_status'] == 2) {echo 'Part Waiting';}
else if ($qr['rc_status'] == 3) {echo 'Complete';}
else if ($qr['rc_status'] == 4) {echo 'Beyond Repair';}
else if ($qr['rc_status'] == 5) {echo 'In Progress';}
else {echo 'Error: Status value is not a expected / possible value.';}
print"</td><td><font color=\"green\">Edit</font> | <font color=\"red\">X</font></tr>";
$alternate++;
}
print "<table>";
}
else
{
if($db->num_rows($q1) == 0)
{
print "Sorry, we could not find a repair with that ID, check your source.";
}
if($db->num_rows($q1) == 1)
{
print "<fieldset>
<script>
function ins_apple(){
var text = \"Apple\";
document.forms.edit.make.value = text;
}
function ins_microsoft(){
var text = \"Microsoft\";
document.forms.edit.make.value = text;
}
function isn_hp(){
var text = \"HP\";
document.forms.edit.make.value = text;
}
function ins_dell(){
var text = \"Dell\";
document.forms.edit.make.value = text;
}
function ins_samsung(){
var text = \"Samsung\";
document.forms.edit.make.value = text;
}
function ins_toshiba(){
var text = \"Toshiba\";
document.forms.edit.make.value = text;
}
function ins_asus(){
var text = \"Asus\";
document.forms.edit.make.value = text;
}
function ins_lenovo(){
var text = \"Lenovo\";
document.forms.edit.make.value = text;
}
function ins_iphone(){
var text = \"iPhone\";
document.forms.edit.device.value = text;
}
function ins_ipod(){
var text = \"iPod\";
document.forms.edit.device.value = text;
}
function ins_ipad(){
var text = \"iPad\";
document.forms.edit.device.value = text;
}
function ins_generic_tablet(){
var text = \"Generic Tablet\";
document.forms.edit.device.value = text;
}
</script>
<form name='edit' method='post'>
<input type=\"hidden\" name=\"posted\" value=\"TRUE\">
<table width =\"80%\" border=\"1\"><tr style='background:lightblue'><th colspan=\"4\"><h1>Editing record for {$fq['rc_fname']} {$fq['rc_lname']}</h1></th></tr><tr><td>
<tr class='bgalt1'><td><label for='name'>First Name:</label></td><td><input type='text' name='first_name' id=\"name\" value=\"{$fq['rc_fname']}\" /></td>
<td><label for='lname'>Last Name: </label></td><td><input type='text' id='lname' name='last_name' value=\"{$fq['rc_lname']}\" /></td></tr>
<tr class='bgalt3'><td><label for='email'>Email:</label></td><td> <input type='text' id='email' name='email' value=\"{$fq['rc_email']}\" /></td>
<td>Contact Number:</td><td><input type='text' name='contact_no' value=\"{$fq['rc_contactno']}\"/></td></tr>
<tr class='bgalt1'><td><label for='make'>Make: </label></td>
<td><input type='text' id='make' name='make' value=\"{$fq['r_oem']}\" /><br />
<input onclick='ins_apple()' type='button' value='Apple' id='button'>
<input onclick='ins_microsoft()' type='button' value='Microsoft' id='button'>
<input onclick='ins_hp()' type='button' value='HP' id='button'>
<input onclick='ins_dell()' type='button' value='Dell' id='button'><br />
<input onclick='ins_samsung()' type='button' value='Samsung' id='button'>
<input onclick='ins_toshiba()' type='button' value='Toshiba' id='button'>
<input onclick='ins_asus()' type='button' value='Asus' id='button'>
<input onclick='ins_lenovo()' type='button' value='Lenovo' id='button'>
</td><td>device: </td><td><input type='text' id= 'device' name='device' value=\"{$fq['r_device']}\" /><br />
<input onclick='ins_iphone()' type='button' value='iPhone' id='button'>
<input onclick='ins_ipod()' type='button' value='iPod' id='button'>
<input onclick='ins_ipad()' type='button' value='iPad' id='button'>
<input onclick='ins_generic_tablet()' type='button' value='Generic Tablet' id='button'>
</td></tr>
<tr class='bgalt3'><td>Model: </td><td><input type=\"text\" name=\"model\" value=\"{$fq['r_mod']}\"/></td><td>Price: </td><td><input type='text' name='price' value=\"{$fq['r_price']}\"'/></td></tr>
<tr class='bgalt1'><td>Fault</td><td><input type=\"text\" name=\"fault\" value=\"{$fq['r_reserve']}\" /></td><td>Notes: </td><td><input type=\"text\" name=\"notes\" value=\"{$fq['r_notes']}\" onfocus=\"if (this.value=='Add Notes') this.value='';\"/></td></tr>
<tr class='bgalt3'><td>Status: </td><td>";
if ($fq['rc_status'] == 1) {
echo'<select name="status" value="options">
<option value="1">Received</option>
<option value="2">Part Waiting</option>
<option value="3">Complete</option>
<option value="4">Beyond Repair</option>
<option value="5">In Progress</option>
</SELECT>';
}
else if ($fq['rc_status'] == 2) {
echo'<select name="status" value="options">
<option value="2">Part Waiting</option>
<option value="1">Received</option>
<option value="3">Complete</option>
<option value="4">Beyond Repair</option>
<option value="5">In Progress</option>
</SELECT>';
}
else if ($fq['rc_status'] == 3) {
echo'<select name="status" value="options">
<option value="3">Complete</option>
<option value="1">Received</option>
<option value="2">Part Waiting</option>
<option value="4">Beyond Repair</option>
<option value="5">In Progress</option>
</SELECT>';
}
else if ($fq['rc_status'] == 4) {
echo'<select name="status" value="options">
<option value="4">Beyond Repair</option>
<option value="1">Received</option>
<option value="2">Part Waiting</option>
<option value="3">Complete</option>
<option value="5">In Progress</option>
</SELECT>';
}
else if ($fq['rc_status'] == 5) {
echo'<select name="status" value="options">
<option value="5">In Progress</option>
<option value="1">Received</option>
<option value="2">Part Waiting</option>
<option value="3">Complete</option>
<option value="4">Beyond Repair</option>
</SELECT>';
}
// error with status code. Use default
else {echo'<select name="status" value="options">
<option value="1">Received</option>
<option value="2">Part Waiting</option>
<option value="3">Complete</option>
<option value="4">Beyond Repair</option>
<option value="5">In Progress</option>
</SELECT>';}
print "</td><td><input type=\"checkbox\" name=\"pf\" value=\"1\"> Parts Fitted?</td><td colspan=\"1\"><input type='submit' value='Edit Record' /></form></td></tr>
</table></fieldset>";
// now the notes
if (isset($_GET['notedel'])) {
$selnotestodel=$db->query("SELECT * FROM notes WHERE id={$_GET['notedel']}");
if (mysql_num_rows($selnotestodel)) {
$db->query("DELETE FROM notes WHERE id='{$_GET['notedel']}'");
//print "<div style='background:lightgreen; width:150px'><p><strong>Notes Was Successfully Deleted!</strong></p></div>";
print "<script>alert('Note Deleted Successfully');</script>";
header("location: edit.php?edit={$fq['r_id']}");
}
else
{
print "<div style='background:#FF9494; width:150px'><p><strong>Sorry the note you are trying to delete doesn't appear to exist...</strong></p></div>";
}
}
if (isset($_POST['n_csumbit'])) {
$nsubject = mysql_real_escape_string($_POST['n_subj']);
$nnote = mysql_real_escape_string($_POST['n_comments']);
$npby = mysql_real_escape_string($_POST['n_by']);
$db->query("INSERT INTO notes (linkedtoid, subject, note, postedby) VALUES('{$_GET['edit']}','$nsubject','$nnote','$npby')");
// print "<div style='background:lightgreen; width:150px'><p>Notes Added Successfully.<br /> Added by: {$_POST['n_by']}</p></div>";
print "<script>alert('Note added Successfully');</script>";
header( "Refresh: 0;" );
}
print "<hr /><center><h2>Detailed Notes:</h2></center>
<table width =\"80%\" border=\"1\"><tr style='background:lightblue'><th>Time</th><th>Subject</th><th>Comment</th><th>Made By</th><th>Actions</th></tr>";
if ($db->num_rows($selnotes)) {
while ($nts=$db->fetch_row($selnotes)) {
if ($alternate % 2 == 0){
echo "<tr class='bgalt1'>";
}
else{
echo "<tr class='bgalt3'>";
}
$mysqldate = date('d/m/Y H:i:s', $nts['time'] );
print "
<td width='10%'>
{$nts['time']}
</td><td width='25$'>
{$nts['subject']}
</td><td width='55%'>
{$nts['note']}
</td><td width='5%'>
{$nts['postedby']}
</td><td width='5%'>
<a href='edit.php?edit={$_GET['edit']}&notedel={$nts['id']}' title='Delete Note'><font color=red><b>X</b></font></a>
</td></tr>
";
$alternate++;
}
}
else {
print "<tr class='bgalt4'><td colspan='5'><center><b>No notes on this repair</b></center></td></tr>";
}
print "
<form name='n_commentspost' method='post'><fieldset>
<input type=\"hidden\" name=\"n_csumbit\" value=\"1\">
<tr class='bgalt5'><th colspan='5'>Add New Note</th></tr>
<tr class='bgalt5'>
<td>
Subject
</td>
<td>
Comments
</td>
<td>
Made By
</td>
<td colspan='2'>
Submit
</td>
</tr>
<tr class='bgalt1'>
<td>
<input type=\"text\" name=\"n_subj\"/>
</td>
<td>
<textarea name=\"n_comments\"></textarea>
</td>
<td>
<select name=\"n_by\" value=\"options\">
<option value=\"Jon\">Jon</option>
<option value=\"Jason\">Jason</option>
<option value=\"Clodagh\">Clodagh</option>
</select>
</td>
<td colspan='2'>
<input type='submit' value='Add Note' />
</td>
</tr>
</form></fieldset>
";
print "</table>";
if (isset($_GET['partdel'])) {
$selpartstodel=$db->query("SELECT * FROM usedparts WHERE id={$_GET['partdel']}");
if (mysql_num_rows($selpartstodel)) {
$db->query("DELETE FROM usedparts WHERE id='{$_GET['partdel']}'");
//print "<div style='background:lightgreen; width:150px'><p><strong>Notes Was Successfully Deleted!</strong></p></div>";
print "<script>alert('Part Deleted Successfully');</script>";
header("location: edit.php?edit={$fq['r_id']}");
}
else
{
print "<div style='background:#FF9494; width:150px'><p><strong>Sorry the part you are trying to delete doesn't appear to exist...</strong></p></div>";
}
}
if (isset($_POST['pa_csumbit'])) {
$name = mysql_real_escape_string($_POST['part_name']);
$linkedto = mysql_real_escape_string($_POST['n_comments']);
if (strlen($_POST['item']) > 1) {
$db->query("INSERT INTO usedparts (binded_to, part_name) VALUES('{$_GET['edit']}','{$_POST['item1']}')");
}
else {
$db->query("UPDATE repairs SET part1id={$_POST['item1']} WHERE r_id={$_GET['edit']}");
$db->query("UPDATE stock SET commited=commited+1, s_count=s_count-1 WHERE id={$_POST['item1']}");
$db->query("INSERT INTO usedparts (binded_to, part_name) VALUES('{$_GET['edit']}','$name')");
}
// print "<div style='background:lightgreen; width:150px'><p>Notes Added Successfully.<br /> Added by: {$_POST['n_by']}</p></div>";
print "<script>alert('part added Successfully');</script>";
header( "Refresh: 0;" );
}
print "<hr /><center><h2>Parts Used / Needed For This Job:</h2></center>
<table width =\"80%\" border=\"1\"><tr style='background:lightblue'><th>Part Name</th><th>Failed?</th><th>Actions</th></tr>";
if ($db->num_rows($selparts)) {
$partspart1=$db->query("SELECT * FROM stock WHERE id='{$pts['part_name']}'");
$partss=$db->fetch_row("$partspart1");
while ($pts=$db->fetch_row($selparts)) {
if ($alternate % 2 == 0){
echo "<tr class='bgalt1'>";
}
else{
echo "<tr class='bgalt3'>";
}
print "
<td width='60%'>";
print "{$partss['name']}";
print "
</td><td width='20%'>
{$pts['failed']}
</td><td width='20%'>
<a href='edit.php?edit={$_GET['edit']}&partdel={$pts['id']}' title='Delete Note'><font color=red><b>X</b></font></a>
</td></tr>
";
$alternate++;
}
}
else {
print "<tr class='bgalt4'><td colspan='3'><center><b>No parts used for this repair</b></center></td></tr>";
}
print "
<form name='parts_usedpost' method='post'><fieldset>
<input type=\"hidden\" name=\"pa_csumbit\" value=\"1\">
<tr class='bgalt5'><th colspan='5'>Add A Part</th></tr>
<tr class='bgalt5'>
<td>
Part
</td>
<td colspan='2'>
Submit
</td>
</tr>
<tr class='bgalt1'>
<td>
Part Name:<input type=\"text\" name=\"part_name\"/> or Part: ".item_dropdown1($c,'item1')."
</td>
<td colspan='2'>
<input type='submit' value='Add Part' />
</td>
</tr>
</form></fieldset>
";
print "</table>";
}
print "</div>";
}
?>
I don't know how or is there is an alternate way, but what i need is to
take the $_GET['edit'] use it check my usedparts table to find used parts linked to the id. then needs to display them. Why does that part and only that part not work?
I don't need people to tell me "this should be validated" or this is insecure. its runs on a whitelist, in a local network. security isn't an issue.
EDIT: I've overcome the mysql_fetch_assoc error. Now my problem is i've just realised...
if they use the drop down, part_name is saved as the id.
if they input a new item name, rather than an existing one, it is text.
How can I check if part_name is first an int or text, if its an int, i need to get the name of the stock item from the stock table using that int as the id. then get its name from that row. if its text i just want to output the text as is. how can i check if something is an int, and do something differentially.
Would preg_match be appropriate?
I don't think "$_GET['edit']" is valid using in a string {$_GET['edit']} this way.
It should be like this:
$query = "SELECT * from table WHERE name='".$_GET['edit']."'";
Try to echo the query at C:\wamp\www\dev\includes\class\class_db_mysql.php on line 67 or before this line.
And see what does it returns. You will see then,which part of your query got wrong data.
If it looks good, try to run the query in phpmyadmin and you will see the error.
Also you can use echo mysql_error();
I haven't seen the whole code but you can write this:
WHERE r_id='{$_GET['edit']}'"
like:
WHERE r_id='" . mysql_real_escape_string($_GET['edit']) . "'
I'm fairly certain your query is failing somewhere.
Try this
$query = "SELECT ...";
$result = mysql_query($query) or die(mysql_error());
And the o-so-required please don't use mysql_* it is deprecated

PHP create HTML table from database [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
outputting values from database into html table PHP
I am trying to create a table in my .php document which is populated with values from a table in a database. but i cannot get it to work.
Firstly it is not deleting values when there are more than 1 row (There can only ever be 1 item on that particular day)
Secondly if there is no data for a particular day it just puts it into the cell before it, meaning it is on the wrong day.
Here is the code:
<?php
if(!empty($_POST['recipe'])) {
$week = mysql_real_escape_string($_POST['week']);
$day = mysql_real_escape_string($_POST['day']);
$mealtime = mysql_real_escape_string($_POST['mealtime']);
$recipe = mysql_real_escape_string($_POST['recipe']);
$check = mysql_query("SELECT * FROM menu WHERE dayid = '".$day."' AND mealtimeid = '".$mealtime."'");
if(mysql_num_rows($check) == 1) {
mysql_query("DELETE FROM menu WHERE mealtimeid = '".$mealtime."' AND dayid = '".$day."'");
$success = mysql_query("INSERT INTO menu (weekid, dayid, mealtimeid, recipeid)
VALUES('".$week."', '".$day."', '".$mealtime."', '".$recipe."')");
if($success) {
echo "<h1>Success</h1>";
echo "<p>Your recipe was successfully added.</p>";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry there was a problem, please try again.</p>";
}
}
else {
$success = mysql_query("INSERT INTO menu (weekid, dayid, mealtimeid, recipeid) VALUES('".$week."', '".$day."', '".$mealtime."', '".$recipe."')");
if($success) {
echo "<h1>Success</h1>";
echo "<p>Your recipe was successfully added.</p>";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry there was a problem, please try again.</p>";
}
}
}
if(!empty($_POST['selectweek'])) {
$selectweek = mysql_real_escape_string($_POST['selectweek']);
function ouptutMeal($selectweek, $mealtime, $mealname) {
$sqlmeasurement2 = mysql_query("SELECT title, dayid
FROM recipe
JOIN menu ON recipe.recipeid = menu.recipeid
WHERE menu.weekid = '$selectweek'
AND menu.mealtimeid = '$mealtime'
ORDER BY dayid");
echo "<br/>
<table>
<td></td>
<td><strong>Monday</strong></td>
<td><strong>Tuesday</strong></td>
<td><strong>Wednesday</strong></td>
<td><strong>Thursday</strong></td>
<td><strong>Friday</strong></td>
<td><strong>Saturday</strong></td>
<td><strong>Sunday</strong></td>
<tr>
<td><strong>$mealname</strong></td>";
while($info2 = mysql_fetch_array( $sqlmeasurement2 )) {
if(empty($info2['dayid'])) {
echo '<td></td>';
}
elseif($info2['dayid'] == '1') {
echo '
<td>', $info2['title'], '</td>';
}
elseif($info2['dayid'] == '2') {
echo '
<td>', $info2['title'], '</td>';
}
elseif($info2['dayid'] == '3') {
echo '
<td>', $info2['title'], '</td>';
}
elseif($info2['dayid'] == '4') {
echo '
<td>', $info2['title'], '</td>';
}
elseif($info2['dayid'] == '5') {
echo '
<td>', $info2['title'], '</td>';
}
elseif($info2['dayid'] == '6') {
echo '
<td>', $info2['title'], '</td>';
}
else {
echo '
<td>', $info2['title'], '</td>';
}
}
echo '</tr>
</table>';
}
ouptutMeal($selectweek, 1, 'Breakfast');
ouptutMeal($selectweek, 2, 'Lunch');
ouptutMeal($selectweek, 3, 'Evening Meal');
ouptutMeal($selectweek, 4, 'Pudding');
ouptutMeal($selectweek, 5, 'Supper & Snacks');
}
}
else {
?>
This is the form it gets the data from:
<form method="post"
action="">
<fieldset>
<label for="week">Select Week:</label> <select name="week">
<option value="0">
Select Week<?php echo $item; ?>
</option>
</select> <label for="day">Select Day:</label> <select name=
"day">
<option value="0">
Select Day<?php echo $item2; ?>
</option>
</select><br />
<br />
<label for="mealtime">Select Meal Time:</label> <select name=
"mealtime">
<option value="0">
Select Meal Time<?php echo $item3; ?>
</option>
</select><br />
<br />
<label for="recipe">Select Recipe:</label> <select name="recipe">
<option value="0">
Select Recipe<?php echo $item4; ?>
</option>
</select> <input type="submit"
id="login-submit"
value="Add to Menu" />
</fieldset>
</form>
<form method="post"
action="">
<label for="selectweek">Select Week:</label> <select name=
"selectweek">
<option value="0">
Select Week<?php echo $item; ?>
</option>
</select> <input type="submit"
id="login-submit"
value="View Menu" />
</form>
-- The item on the end is meant to be on Sunday but is behind because a previous day does not have a item. How would i make that item go to Sunday, while keeping a gap where the other item isn't.
Use if to check if value is empty or not. Some thing like this.
if($info2['dayid'] == "") {
echo '<td> </td>';
}
it will fill it properly, without disturbing it layout.
Hope this helps.

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