PHP create HTML table from database [duplicate] - php

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.

Related

How to create checkboxs that fetch from database and pass on value

I am new to php and can not turn a row into a checkbox field that passes onto a separate page.
if ($result = $db->query($sql) ) {
//*start of original
if ($result->num_rows > 0) {
?>
<!-- <form action="Confirmation.php" method="post"> -->
<form action="Payment.php" method="post">
<label for="PatientID">Choose the Patient you wish to register for:</label>
<select name="PatientID" id="">
<option value="" disabled>Please select a patient to enroll:</option>
<!-- <option value="All">All Patients</option> -->
<?php
while($result = fetch_assoc($result)) {
echo "<input type='checkbox' value='{$row['PatientID']}'>" . $row['PatientName'] . '</br>';
}
//
//while ($row=$result->fetch_assoc()) {
?>
//<option value="<?=$row['PatientID'];?>"> <?=$row['PatientName']?></option>
//*/ <?php
//}
echo '</select><input type= "submit" class="myButton" name="submit" value="Register Now" /></form>';
} else {
echo "There are no patients currently available for registration." ;
$rosterListFail = true;
}
} else {
$message = $db->error;
// echo $message;
}
//*/
//}
?>

Get text of select box in php page

I have select box in PHP and want text selected item of that:
<form action="" method="get" target="" dir="rtl" class="w3-container">
<?php
echo " <select id='p1' name='p1' >";
echo "<option value='*'>Choose person</option>";
sql code
$result2 = mysql_query($query2,$con);
while($row2 = mysql_fetch_array($result2))
{
$row2['name'];
echo "<option value='".$row2['id']."'>".$row2['name']."</option>";
}
echo " </select>";
mysql_close($con);
?>
<input class="w3-btn w3-hover-yellow" name="" type="submit" value="جستجو">
</form>
<?php
if(isset($_GET['p1']) and $_GET['p1'] != "*")
{
if ($name_insert=trim($_GET["p1"]))
{
if ($strWhere == ""){
$strWhere .= "name_insert='".trim($name_insert)."' ";
$getPage .= "&name_insert=".($name_insert);}
else{
$strWhere .= " and name_insert='".trim($name_insert)."' ";
$getPage .= "&name_insert=".($name_insert);}
}
}
?>
I want code that get text of select box in $name_insert. This code gets value of that.
You can use javascript and save selected option text in a hidden field.
Example
<form action="" method="POST">
<select id="test" onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
<option value="1">Test One</option>
<option value="2">Test Two</option>
</select>
<input type="hidden" name="test_text" id="text_content" value="" />
</form>
PHP
$getOptionText = $_POST['test_text'];
Replace your code with this code
<form action="" method="get" target="" dir="rtl" class="w3-container">
<select id='p1' name='p1' onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
<option value='*'>Choose person</option>
<?php
$result2 = mysql_query($query2,$con);
while($row2 = mysql_fetch_array($result2))
{
echo "<option value='".$row2['id']."'>".$row2['name']."</option>";
}
mysql_close($con);
?>
</select>
<input type="hidden" name="test_text" id="text_content" value="" />
<input class="w3-btn w3-hover-yellow" name="" type="submit" value="جستجو">
</form>
<?php
if(isset($_GET['p1']) and $_GET['p1'] != "*")
{
$getValueOfText = $_GET['test_text'];
echo $getValueOfText;
if ($name_insert=trim($_GET["p1"]))
{
if ($strWhere == ""){
$strWhere .= "name_insert='".trim($name_insert)."' ";
$getPage .= "&name_insert=".($name_insert);}
else{
$strWhere .= " and name_insert='".trim($name_insert)."' ";
$getPage .= "&name_insert=".($name_insert);}
}
}
?>

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

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.

Editing Checkboxes, radios, and dropdowns

I found this site providing code for creating, reading, updating and deleting. I am confused about how to add checkboxes, radio buttons, and dropdowns
http://www.killersites.com/community/index.php?/topic/1969-basic-php-system-vieweditdeleteadd-records/
I'm not concerned with the pagination at all——my primary concern is to be able to put in two dropdowns, yes/no radio button, and a collection of 3 checkboxes using PHP.
My attempts were useless as when I tried to edit choices the values did not stay. Included are my three files: pets, editpets, and view.(I changed the file name for database, etc.)
<?php
function renderForm($first, $last, $pets, $size, $type, $years, $error)
{
?>
<!DOCTYPE html>
<html>
<head>
<title>New Customer</title>
</head>
<body>
<?php
// display possible errors
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>First Name:</strong> <input type="text" name="firstname" value="<?php echo
$first; ?>" />
<strong>Last Name:</strong> <input align="center" type="text" name="lastname" value="<
?php echo $last; ?>" /><br/>
<p><strong>No. Pets </strong>
<select name="pets">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</p>
<br/>
<strong>Size? </strong>
<br/>
Big<input type="radio" value="Yes" name="size" checked><?php echo $size; ?><br />
Small<input type="radio" value="No" name="size"<?php echo $size; ?><br />
<br />
<p><strong>Type</strong><br/>
<input name="type[]" type="checkbox" id="type[]"/>
Cats
<input name="type[]" type="checkbox" id="type[]"/>
Dogs
<input name="type[]" type="checkbox" id="type[]"/>
Others
</p>
<br/>
<strong>Years? </strong>
<select name="year">
<option value="Five or Less">Five or More</option>
<option value="Six or More">Six or More</option>
</select><br/>
<input style="color:purple;" type="submit" name="submit" value="Create My Order :-)">
</div>
</form>
<center>Click Here for Orders</center>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if my form submits and, upon triumph, process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, check its validity
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));
$pets = $_POST['pets'];
$size = mysql_real_escape_string(htmlspecialchars($_POST['size']));
$type = serialize(mysql_real_escape_string(implode(',', $_POST['type'])));
$years = mysql_real_escape_string(htmlspecialchars($_POST['years']));
// check to make sure everything is filled!
if ($firstname == '' || $lastname == '' || $pets == '' || $size == '' || $type == '' || $years == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, show the form again
renderForm($firstname, $lastname, $pets, $size, $type, $years, $error);
}
else
{
// save the data to the database
mysql_query("INSERT customers SET firstname='$firstname', lastname='$lastname', pets='$pets', size='$size', type='$type', years='$years'")
or die(mysql_error());
// once saved, redirect to cheview page
header("Location: view.php");
}
}
else
// if the form is not submitted, show my form again.
{
renderForm('','','','','','','');
}
?>
<?php
$types = array("Cats", "Dogs", "Others");
function renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?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="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>First Name: </strong> <input type="text" name="firstname" value="<?php echo $firstname; ?>" /><br/>
<strong>Last Name: </strong> <input type="text" name="lastname" value="<?php echo $lastname; ?>" /><br/>
<p><strong>No. Pets </strong>
<select name="pets">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</p>
<strong>Size? </strong>
<br/>
Big<input type="radio" value="Yes" name="size" checked><?php echo $size; ?><br />
Small<input type="radio" value="No" name="size"<?php echo $size; ?><br />
<br />
<br />
<br />
<p><strong>Type</strong><br/>
<input name="type[]" type="checkbox" id="type[]"/>
Cats
<input name="type[]" type="checkbox" id="type[]"/>
Dogs
<input name="type[]" type="checkbox" id="type[]"/>
Others
</p>
<br/>
<strong>Years? </strong>
<select name="year">
<option value="Five or Less">Five or More</option>
<option value="Six or More">Six or More</option>
</select><br/>
<br /><br />
<input type="submit" name="submit" value="Resubmit My Order :-)">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// check for id being an integer
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));
$pets = $_POST['pets'];
$size = mysql_real_escape_string(htmlspecialchars($_POST['size']));
$type = serialize(mysql_real_escape_string(implode(',', $_POST['type'])));
$years = mysql_real_escape_string(htmlspecialchars($_POST['years']));
// check that firstname/lastname fields are both filled in
if ($firstname == '' || $lastname == '' || $pets == '' || $size == '' || $type == '' || $years == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE customers SET firstname='$firstname', lastname='$lastname', pets='$pets', size='$size', type='$type', years='$years' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: 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['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM customers WHERE id='$id' ")
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
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$pets = $row['pets'];
$size = $row['size'];
$type = serialize($row['type']);
$years = $row['years'];
// show form
renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, '');
}
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!';
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View customer orders</title>
</head>
<body>
<?php
include('connect-db.php');
$result = mysql_query("SELECT * FROM customers")
or die(mysql_error());
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Pets</th>
<th>Size</th>
<th>Type</th>
<th>Years</th>
<th></th>
<th></th>
</tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
echo '<td>' . $row['pets'] . '</td>';
echo '<td>' . $row['size'] . '</td>';
echo '<td>' . $row['type']. '</td>';
echo '<td>' . $row['years'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
I'm honestly lost at this point. I've been working on this for an entire month and I have no idea what I'm doing any more. I'd be so thankful if anyone can help me to edit this to work.
Thanks everyone.
Right, to get your saved results from the database I'm sure you're aware of how to do this.
For your radio buttons you're going to want to select your 'size' value from the database and use an if statement to determine which radio button will be 'checked'
forename/surname is a matter of simply getting the forename/surname from database and setting the appropriate input tags to the acquired values
You've already posted a technique for handling the combo/drop-down boxes
you'd perform a similar process for the 'type' checkboxes, compare your database values to the values of your checkbox input tags and if the value matches, set the checkbox to checked.
Next time please be more specific in what you are asking for help with and separate your code into segments that correspond with the files it is contained in.
if you have 3 files, have a code block for each file.

Categories