Having problems getting info from database - php

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

Related

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

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

MySQL php edition table and adding the same value on another table

I actually developping an intranet solution for my work,
The thing is that i want to update and operation and add the same result into one of my 3 different tables depending on the -operation- option,
in my initial code if the modification is ok the data will be updated into "taches_redaction" table,
in revenche i need to add 3 different rules,
soif operation is equal to 1 up date taches_redction and add the data into copie table,
soif operation is equal to 2 up date taches_redction and add the data into colla table,
soif operation is equal to 3 up date taches_redction and add the data into archive table,
all of this to have a precise historical record on echa changes in my operations and have some values to get statistics for each team member on the company...
<?php
include '../theme/header-global.php';
?>
<?php
/*
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($serie, $user_id, $journee, $titre, $region, $role, $operation, $date, $error)
{
?>
<div style="width:100%">
<center><h1>تحيين التوزيع</h1></center>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="serie" value="<?php echo $serie; ?>" readonly="readonly" />
<table cellpadding="3" cellpadding="3" align="center" id=MyTable width="650">
<tr>
<td align="center">الإسم</td>
<td align="center">
<?php
// get results from database
$usage = mysql_query("SELECT t.* , o.* FROM users t,taches_redaction o WHERE t.id=o.user_id GROUP BY user_name")
or die(mysql_error());
while($row = mysql_fetch_assoc( $usage )) {
if($row['user_id'] == $user_id)
{ // echo out the contents of each row into a table
echo '' . $row['user_name'] . '';
} else {
// do something else
echo '';
}
}
?>
</td>
<td>
<select id="user_id" name="user_id">
<option value="0"></option>
<?php
$sql = mysql_query('SELECT * FROM users');
while($row = mysql_fetch_array($sql)){
if($row['id'] == $user_id)
{
echo '<option value=' . $row['id'] . ' selected=selected>' . $row['user_name'] . '</option>';
} else {
// do something else
echo '<option value=' . $row['id'] . '>' . $row['user_name'] . '</option>';
}
}
?>
</select>
</td>
</tr>
<tr>
<td align="center">اليومية</td>
<td align="center"><input type="text" name="journee" value="<?php echo $journee; ?>" /></td>
<td></td>
</tr>
<tr>
<td align="center">الرسم العقاري</td>
<td align="center">
<input type="text" name="titre" value="<?php echo $titre; ?>" />
<?php if (!empty($region) && $region == '4' ) echo 'FR'; ?>
<?php if (!empty($region) && $region == '1') echo 'بن عروس'; ?>
<?php if (!empty($region) && $region == '2') echo 'زغوان'; ?>
<?php if (!empty($region) && $region == '3') echo 'تونس'; ?>
</td>
<td>
<select name="region">
<option value="4" <?php if (!empty($region) && $region == '4' ) echo 'selected = "selected"'; ?>>FR</option>
<option value="1" <?php if (!empty($region) && $region == '1') echo 'selected = "selected"'; ?>>بن عروس</option>
<option value="2" <?php if (!empty($region) && $region == '2') echo 'selected = "selected"'; ?>>زغوان</option>
<option value="3" <?php if (!empty($region) && $region == '3') echo 'selected = "selected"'; ?>>تونس</option>
</select>
</td>
</tr>
<tr>
<td align="center">المهام</td>
<td align="center">
<select id="role" name="role">
<option value="0"></option>
<option></option>
</select>
</td>
<td>
</td>
</tr>
<tr>
<td align="center">العملية</td>
<td align="center">
<?php
$fonki = mysql_query("SELECT * FROM fonctions")
or die(mysql_error());
// get results from database
$operage = mysql_query("SELECT t.* , o.* FROM taches_redaction t,operations o WHERE t.operation=o.oper_id GROUP BY operation")
or die(mysql_error());
// display data in table
/* echo "<p><b>View All</b> | <a href='view-paginated.php?page=1'>View Paginated</a></p>"; */
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_assoc( $operage )) {
if($row['oper_id'] == $operation)
{ // echo out the contents of each row into a table
echo '' . $row['operation_name'] . '';
} else {
// do something else
echo '';
}
}
?>
</td>
<?php
echo "<td>
<select name=operation>
<option value =0></option>";
include "../render/render_operation-selected.php";
echo "</select>
</td>";
?>
</tr>
<tr>
<td>تاريخ التحيين</td>
<td>
<?php
echo '' . $row['date'] . '';
?>
</td>
<td style="direction:rtl;">
<?php echo "<input type='text' value='".date('o/m/d')."' style='width: 148px;' name='date' readonly=readonly>";?>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="تغيير" class="brd"></td>
<td align="center">
<input type="submit" value="إلغاء" onClick="history.go(-1);return true;" class="bbl">
</td>
</tr>
</table>
<?php
}
// connect to the database
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['serie']))
{
// get form data, making sure it is valid
$serie = $_POST['serie'];
$user_id = mysql_real_escape_string(htmlspecialchars($_POST['user_id']));
$journee = mysql_real_escape_string(htmlspecialchars($_POST['journee']));
$titre = mysql_real_escape_string(htmlspecialchars($_POST['titre']));
$region = mysql_real_escape_string(htmlspecialchars($_POST['region']));
$role = mysql_real_escape_string(htmlspecialchars($_POST['role']));
$operation = mysql_real_escape_string(htmlspecialchars($_POST['operation']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
// check that firstname/lastname fields are both filled in
if ($user_id == '' || $journee == '' || $titre == '' || $region == '' || $role == '' || $operation =='' || $date =='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($serie, $user_id, $journee, $titre, $region, $role , $operation, $date, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE taches_redaction SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date' WHERE serie='$serie'")
/* frere update */
/*
AND
mysql_query("INSERT copie SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date'")
AND
mysql_query("INSERT colla SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date'")
AND
mysql_query("INSERT archive SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date'")
*/
or die(mysql_error());
// once saved, redirect back to the view page
/* header('Refresh: 2; URL = taches_view.php');
*/
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['serie']) && is_numeric($_GET['serie']) && $_GET['serie'] > 0)
{
// query db
$serie = $_GET['serie'];
$result = mysql_query("SELECT * FROM taches_redaction WHERE serie=$serie")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$serie = $row['serie'];
$user_id = $row['user_id'];
$journee = $row['journee'];
$titre = $row['titre'];
$region = $row['region'];
$role = $row['role'];
$operation = $row['operation'];
$date = $row['date'];
// show form
renderForm($serie, $user_id, $journee, $titre, $region, $role, $operation, $date, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
<!-- end .content --></div>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<?php
include '../theme/footer-global.php';
?>

How to pass the selected value in dropdown (HTML) to PHP

I am building a select option dynamically. I am selecting from the select option, one value. (values for list come from php
How can I pass that selected value to PHP?
<select id ="s1" name="swimopt" class="so">
<?php echo $options; ?>
</select>'
THe $options are coming from a MySQL and populating the dropdown
When I select a value, and try
echo $_POST['swimopt'];
does not show selected value
Please help
<form id="swimdata" method="POST" action="save.php">
<input type="radio" style="font-size: 16px;font-weight: bolder" name="gender" class ="gender" value="boys">BOYS
<input type="radio" style="font-size: 16px;font-weight: bolder" name="gender" class ="gender" value="girls">GIRLS
<table id="meetTable" style="width:auto">
<tr>
<th>EVENT:</th>
<th>NAME:</th>
<th>LANE:</th>
<th>TIME:</th>
<th>PLACE:</th>
<th>SCORE 1:</th>
<th>SCORE 2:</th>
<th>PLACE:</th>
<th>TIME:</th>
<th>LANE:</th>
<th>NAME:</th>
</tr>
</table>
<input type="submit" name="formSubmit" value="Submit" />
<input type="hidden" name="action1" value="addSwimmer" id="action1">
</form>
This is my PHP getting the $options from mySQL
if ($result->num_rows > 0) {
$options= '';
// output data of each row
while($row = $result->fetch_assoc()) {
$options .= "<tr><td>" . $row["swimmer_id"]. "</td><td>" . $row["first_name"]. " " . $row["last_name"]. " </td><td> " . $row["school_name"]. "</td></tr>";
}
} else {
echo "0 results";
}
echo $options;
$conn->close();
ScreenShots:
Options echoed into select box:
<select id ="s1" name="swimopt" class="so">
<?php echo $options; ?>
</select>'
PHP file code
$sql = "select first_name, last_name from swimming where gender='m'";
$results = mysqli_query($link,$sql);
if ($results->num_rows > 0) {
$options = '';
// output data of each row
while($row = $results->fetch_assoc()) {
$fname=$row["first_name"];
$lname=$row["last_name"];
$options .= "<option value= >" . $row["first_name"] . " " . $row["last_name"]."</option>";
}
} else {
echo "0 results";
}
echo $options;
$link->close();
?>
I think I see what your problem is. You're not setting a select option.
Try this:
<?php
$options = 'John';
?>
<form id="swimdata" method="POST" action="save.php">
<input type="radio" style="font-size: 16px;font-weight: bolder" name="gender" class ="gender" value="boys">BOYS
<input type="radio" style="font-size: 16px;font-weight: bolder" name="gender" class ="gender" value="girls">GIRLS
<table id="meetTable" style="width:auto">
<tr>
<th>EVENT:</th>
<th>NAME:</th>
<th>LANE:</th>
<th>TIME:</th>
<th>PLACE:</th>
<th>SCORE 1:</th>
<th>SCORE 2:</th>
<th>PLACE:</th>
<th>TIME:</th>
<th>LANE:</th>
<th>NAME:</th>
</tr>
</table>
<select id ="s1" name="swimopt" class="so" value="">
<?php
for($i=0;$i<10;$i++){
echo '<option value="user '.$i.'" >user '.$i.'</option>';
}
?>
</select>
<input type="submit" name="formSubmit" value="Submit" />
<input type="hidden" name="action1" value="addSwimmer" id="action1">
</form>
The select option must be wrapped with html tag <option> with a value attribute, which will be posted if it is selected.
According to your given code you are not generating options for a select. So try something like this:
if ($result->num_rows > 0) {
$options= '';
// output data of each row
while($row = $result->fetch_assoc()) {
$options .= "<option value=\"". $row["swimmer_id"] ."\">" . $row["first_name"]. " " . $row["last_name"]. " - " . $row["school_name"]. "</option>";
}
} else {
echo "0 results";
}
echo $options;
$conn->close();
Now if you $_POST it you will get the swimmer id

Refine Results with dropdown box

I would like to refine the results of mysql query using dropdown boxes... live site is here:
http://www.halfwayenterprises.com/search/tyrell.php
<form name="doublecombo" action="" method="POST">
<label for="status">Status:</label>
<label for="current">
<input class="radio_style" id="current" checked="checked" name="status" type="radio" value="current">
Current
</label>
<label for="obsolete">
<input class="radio_style" id="obsolete" name="status" type="radio" value="obsolete">
Obsolete
</label>
<label for="both">
<input class="radio_style" id="both" name="status" type="radio" value="both">
ALL
</label>
<br /><br />
<select name="category" size="1" onChange="redirect(this.options.selectedIndex)">
<option value="null">Category</option>
<option value="asset management">Asset Management</option>
<option value="budget">Budget/Finance</option>
<option value="central office">Central Office</option>
<option value="disposal">Disposal</option>
</select>
<select name="subcategory">
<option value="null">Sub-Category</option>
<option value="Portfolio">Portfolio</option>
<option value="Pricing">Pricing</option>
<option value="Valuation">Valuation</option>
<option value="Disposal">Disposal</option>
</select>
<input name="submitted" type="submit" value="GO">
<br />
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option id="title" VALUE="title">Title</option>
<Option id="poc" VALUE="poc">POC</option>
<Option id="purpose" VALUE="purpose">Purpose</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input name="submitted" type="submit" value="GO">
</form>
<select name="filter1">
<option value="az">Sort by A-Z</option>
<option value="date">Sort by Date</option>
</select>
<select name="filter2">
<option value="office">Sort by Office</option>
<option value="p">P</option>
<option value="pt">PT</option>
<option value="pf">PF</option>
</select>
<select name="filter3">
<option value="mandatory">Mandatory</option>
<option value="nonmandatory">Non-Mandatory</option>
<option value="combined">Combined</option>
</select>
</form>
</p>
<script>
<!--
/*
Double Combo Script Credit
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free JavaScripts here!
*/
var groups=document.doublecombo.category.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=new Option("Sub Category")
group[1][0]=new Option("Portfolio")
group[1][1]=new Option("Pricing")
group[1][2]=new Option("Valuation")
group[3][0]=new Option("Central Office")
group[4][0]=new Option("Disposal")
var temp=document.doublecombo.subcategory
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function go(){
location=temp.options[temp.selectedIndex].value
}
//-->
</script>
<?
mysql_connect("localhost", "name", "pasword") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
if(isset($_POST["submitted"])){
$status = $_POST['status'];
$category = $_POST['category'];
$subcategory = $_POST['subcategory'];
echo '<div class="status_div">';
if($status=='current')
{
echo "<h2>Results</h2><p>";
$res = mysql_query("SELECT * FROM material WHERE status='$status' AND category='$category' AND subcategory='$subcategory' ORDER BY `documentid` ASC");
while ($row = mysql_fetch_assoc($res)) {
echo '<div class="current">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
} if ($status=='obsolete')
{
echo "<h2>Results</h2><p>";
$res = mysql_query("SELECT * FROM material WHERE status='$status' AND category='$category' ORDER BY `documentid` ASC ");
while ($row = mysql_fetch_assoc($res)) {
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '<br>';
}
} if ($status=='both')
{
echo "<h2>Results</h2><p>";
$res = mysql_query("SELECT * FROM material WHERE status1='both' AND category='$category' ORDER BY `documentid` ASC");
while ($row = mysql_fetch_assoc($res)) {
echo '<div class="">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
}
echo '</div>';
}
$field = #$_POST['field'] ;
$find = #$_POST['find'] ;
$searching = #$_POST['searching'] ;
$status = $_POST['status'];
//This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo "<h2></h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<a href='tyrell.htm'>Return</a>";
exit;
}
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
if($status=='current'){
$data = mysql_query("SELECT * FROM material WHERE status='$status' AND lower($field) LIKE'%$find%' LIMIT 0,30");
while ($row = mysql_fetch_assoc($data)) {
echo '<div class="current">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
}
if ($status=='obsolete'){
$data = mysql_query("SELECT * FROM material WHERE status='$status' AND lower($field) LIKE'%$find%' LIMIT 0,30");
while ($row = mysql_fetch_assoc($data)) {
echo '<div class="obsolete">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
} if ($status=='both'){
$data = mysql_query("SELECT * FROM material WHERE status1='both' AND lower($field) LIKE'%$find%' LIMIT 0,30");
while ($row = mysql_fetch_assoc($data)) {
echo '<div class="">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
<p align="center"><font face="arial" size="-2">This free script provided by</font><br>
<font face="arial, helvetica" size="-2"><a href="http://javascriptkit.com">JavaScript
Kit</a></font></p>'
</body>
</html>
I have can't think of how to use the drop downs without having a submit button
I think I know what you need...
Use jquery to submit form on you page.
Something like this...
$("submitted").click(function() {
var url = "file.php";
$.ajax({
type: "POST",
url: url,
data: $("doublecombo").serialize(), // serializes the form's elements.
success: function(data)
{
// populate box or div with your result
}
});
return false; // avoid reload.
});
//PHP part
if($_POST['someField']){
$result = //Do query and staff and return any type of resposne you will handle in ajax success
echo $result;
exit;
}
You can use JavaScript to manipulate the content of the dropdown list. All you need is to do is bind the click even on the radio button and when one of them gets clicked, use an Ajax call to retrieve the information from your SQL database and modify the content of your selectbox.
EDIT
Here's some code you can add to your page:
$('form[name=doublecombo] input').change(function() {
$('form[name=doublecombo]').submit();
});
Note that change might not work. If it doesn't, try using click instead.

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.

Categories