Post New Checkbox values to db after edited - php

I have a edit form that has some checkboxes on it and I am having trouble getting the new checkbox values posted back to the db after it has been changed. So far the form will load in the current values in the db but after you click different check boxes it wont update the change in the db. Any help would be appreciated.
<?php
/*
EDIT.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($id, $firstname, $contactname, $phone, $type, $sex, $markers, $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>Contact Name: *</strong> <input type="text" name="contactname" value="<?php echo $contactname; ?>"/><br/>
<strong>Phone Number: *</strong> <input type="text" name="phone" value="<?php echo $phone; ?>"/><br/>
<strong>Type: *</strong>
<select name="type">
<option value="">Select...</option>
<option value="Inpatient Hospital" <?php if($type=="Inpatient Hospital")echo "selected=\"selected\""; ?>>Inpatient Hospital</option>
<option value="Residential Facility"<?php if($type=="Residential Facility")echo "selected=\"selected\""; ?>>Residential Facility</option>
<option value="Behavioral Treatment Facility"<?php if($type=="Behavioral Treatment Facility")echo "selected=\"selected\""; ?>>Behavioral Treatment Facility</option>
<option value="Therapeutic Group Home"<?php if($type=="Therapeutic Group Home")echo "selected=\"selected\""; ?>>Therapeutic Group Home</option>
<option value="Drug or Addictions Rehab"<?php if($type=="Drug or Addictions Rehab")echo "selected=\"selected\""; ?>>Drug or Addictions Rehab</option>
</select><br/>
<input type="radio" name="sex" value="Male" <?php echo ($sex=="Male")?'checked="checked"':'' ?>size="17">Male
<input type="radio" name="sex" value="Female" <?php echo ($sex=="Female")?'checked="checked"':'' ?> size="17">Female
<input type="radio" name="sex" value="Both" <?php echo ($sex=="Both")?'checked="checked"':'' ?> size="17">Both<br/>
<strong>Markers: *</strong> <input type="text" name="markers" value="<?php echo $markers; ?>"/><br/>
<?php
// Create connection
$con=mysqli_connect("localhost","un","pw","childcare");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT FMarkers FROM faci WHERE ID='$id'");
while($row = mysqli_fetch_array($result))
{
$focus=explode(",",$row['FMarkers']);
?>
Autism<input type="checkbox" name="FMarkers[]" value="Autism" <?php if(in_array("Autism",$focus)) { ?> checked="checked" <?php } ?> >
Attachement Disorder<input type="checkbox" name="FMarkers[]" value="Attachement Disorder" <?php if(in_array("Attachement Disorder",$focus)) { ?> checked="checked" <?php } ?> >
Dissociative Disorder<input type="checkbox" name="FMarkers[]" value="Dissociative Disorder" <?php if(in_array("Dissociative Disorder",$focus)) { ?> checked="checked" <?php } ?> >
ODD<input type="checkbox" name="FMarkers[]" value="ODD" <?php if(in_array("ODD",$focus)) { ?> checked="checked" <?php } ?> >
ADHD<input type="checkbox" name="FMarkers[]" value="ADHD" <?php if(in_array("ADHD",$focus)) { ?> checked="checked" <?php } ?> >
<?php
//print_r(array_values($focus));
//echo("<pre>\n");
//print_r($_POST);
//echo("</pre>\n");
//var_dump($dog);
//these below are different ways I have tried to get it to work
//$markers = implode(',', $_POST['dog']);
//$markers=$_POST['focus'];
//$markers = implode(",",$markers);
//$markers = implode(",",$_POST['focus']);
//$check = isset($_POST['focus']) ? $_POST['focus'] : '';
//$markers = is_array($check) ? implode(", ", $check) : '';
//echo $markers;
?>
<?php
}
?>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</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']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$contactname = mysql_real_escape_string(htmlspecialchars($_POST['contactname']));
$phone = mysql_real_escape_string(htmlspecialchars($_POST['phone']));
$type = mysql_real_escape_string(htmlspecialchars($_POST['type']));
$sex = mysql_real_escape_string(htmlspecialchars($_POST['sex']));
$markers = mysql_real_escape_string(htmlspecialchars($_POST['markers']));
// check that firstname/lastname fields are both filled in
if ($firstname == '' || $contactname == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $firstname, $contactname, $phone, $type, $sex, $markers, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE faci SET FName='$firstname', FContact='$contactname', FPhone='$phone', FType='$type', FSex='$sex', FMarkers='$markers' WHERE ID='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: facility-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 faci 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['FName'];
$contactname = $row['FContact'];
$phone = $row['FPhone'];
$type = $row['FType'];
$sex = $row['FSex'];
$markers = $row['FMarkers'];
// show form
renderForm($id, $firstname, $contactname, $phone, $type, $sex, $markers, '');
}
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!';
}
}
?>

Related

How to create a selection dropdown in php form

I am working on a project and would like to give the user per-determined values when updating a record.
Here is my code so far.
<?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>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</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']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$Name = mysql_real_escape_string(htmlspecialchars($_POST['Name']));
$Status = mysql_real_escape_string(htmlspecialchars($_POST['Status']));
$Comments = mysql_real_escape_string(htmlspecialchars($_POST['Comments']));
$Type = mysql_real_escape_string(htmlspecialchars($_POST['Type']));
// check that firstname/lastname fields are both filled in
if ($Name == '' || $Type == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $Name, $Status, $Comments, $Type, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE Schools SET Name='$Name', Status='$Status', Comments='$Comments', Type='$Type' 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 Schools 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
$Name = $row['Name'];
$Status = $row['Status'];
$Comments = $row['Comments'];
$Type = $row['Type'];
// show form
renderForm($id, $Name, $Status, $Comments, $Type, '');
}
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!';
}
}
?>
I am wanting to replace the status text filed with a drop down list of options.
Replace your <input by <select :
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<!-- <strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>-->
<strong>Status:</strong> <select name="Status">
<option value="1">Status 1</option>
<option value="2">Status 2</option>
</select>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
If your statuses are in a table, fill the <select> with a query :
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>School Name:</strong> <input type="text" name="Name" value="<?php echo $Name; ?>"/><br/><br>
<!-- <strong>Status:</strong> <input type="text" name="Status" value="<?php echo $Status; ?>"/><br/><br>-->
<strong>Status:</strong> <select name="Status">
<?php
$result = mysql_query("SELECT * FROM tbl_status",$cnx);
while ( $row = mysql_fetch_array($result) )
echo "<option value='" . $row["id"] . "'>" . $row["text"] . "</option>";
?>
</select>
<strong>Comments:</strong> <input type="text" name="Comments" value="<?php echo $Comments; ?>"/><br/><br>
<strong>Type:</strong> <input type="text" name="Type" value="<?php echo $Type; ?>"/><br/><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
You could use the html <datalist> or the <select> tag.
I hope I could help.
First of all you need to switch from mysql_* to mysqli_* as it going to get removed in php 7.0 I'm using this function i created and it might help you
here is the php code
function GetOptions($request)
{
global $con;
$sql = "SELECT * FROM data GROUP BY $request ORDER BY $request";
$sql_result = mysqli_query($con, $sql) or die('request "Could not execute SQL query" ' . $sql);
while ($row = mysqli_fetch_assoc($sql_result)) {
echo "<option value='" . $row["$request"] . "'" . ($row["$request"] == $_REQUEST["$request"] ? " selected" : "") . ">" . $row["$request"] . "$x</option>";
}
}
and the html code goes like
<label>genre</label>
<select name="genre">
<option value="all">all</option>
<?php
GetOptions("genre");
?>
</select>

edit_subject.php is not working, the error is saying about database query failed

This is kind of the error I'm getting:
Database query failed.
I've uploaded this webpage: http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1
Here's my file:
<?php require_once("../includes/session.php"); ?>
<?php require_once("../includes/db_connection.php"); ?>
<?php require_once("../includes/functions.php"); ?>
<?php require_once("../includes/validation_functions.php"); ?>
<?php find_selected_page(); ?>
<?php
if (!$current_subject)
{
// subject ID was missing or invalid or
// subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit']))
{
// validations
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors))
{
// Perform Update
$id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "UPDATE subjects SET ";
$query .= "menu_name='{$menu_name}', ";
$query .= "position={$position}, ";
$query .= "visible={$visible} ";
$query .= "WHERE id={$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) >= 0)
{
// Success
$_SESSION["message"] = "Subject updated.";
redirect_to("manage_content.php");
}
else
{
// Failure
$message = "Subject update failed.";
}
}
}
// else
// {
// // This is probably a GET request
// }
?>
<?php include("../includes/layouts/header.php"); ?>
<div id="main">
<div id="navigation">
<?php
echo navigation($current_subject, $current_page);
?>
</div>
<div id="page">
<?php
// echo message();
// $message is just a variable, doesn't use the SESSION
if(!empty($message))
{
echo "<div class=\"message\">" . htmlentities($message) . "</div>";
}
?>
<?php echo form_errors($errors); ?>
<h2>Edit Subject: <?php echo htmlentities($current_subject["menu_name"]); ?></h2>
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="<?php echo htmlentities($current_subject["menu_name"]); ?>" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows($subject_set);
for ($count=1; $count <= $subject_count; $count++)
{
echo "<option value=\"{$count}\"";
if ($current_subject["position"] == $count)
{
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" <?php if ($current_subject["visible"] == 0) { echo "checked"; } ?> /> No
<input type="radio" name="visible" value="1" <?php if ($current_subject["visible"] == 1) { echo "checked"; } ?> /> Yes
</p>
<input type="submit" name="submit" value="Edit Subject" />
</form>
<br />
Cancel
Delete Subject
</div>
The problem is somewhere else and not with your UPDATE query actually. If you see the link you posted, you are passing subject parameter with url, whose value is 1 which is integer.
Now when you click submit it's changing the url to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=About%20Widget%20Corp .
Here as you see the subject parameter is not integer but string value name of subject. And that is causing the problem.
You are getting error as it's not retrieving the subject data from database correctly because of wrong id type. You just need to make sure the form is being posted to right url, which would be http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1.
You need to correct the action parameter on the <form> tag for that.
Look for the line below in your code:
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
And change it to
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["id"]); ?>" method="post">
If you see, now the form will be submitted to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1, which is the correct url.

How to validate input field in update profile of a user

The Below code is the profile login system update user pade:
In the below code i have already data in the text box(retrive data from database). i want to validate if i erase data and submit:
help me friends i want to validate the input field if the input field is empty:
<?php
session_start(); // Must start session first thing
// Here we run a login check
if (!isset($_SESSION['id'])) {
echo 'Please log in to access your account';
exit();
}
//Connect to the database through our include
include_once "database.php";
// Place Session variable 'id' into local variable
$id = $_SESSION['id'];
// Process the form if it is submitted
if ($_POST['qualific']) {
$fullname = $_POST['fullname'];
$contact = $_POST['contact'];
$qualific = $_POST['qualific'];
$sql = mysql_query("UPDATE jobseeker_members SET fullname='$fullname', contact='$contact', qualification='$qualific' WHERE id='$id'");
echo 'Your account info has been updated, visitors to your profile will now see the new info.<br /><br />
To return to your profile edit area, click here';
exit();
} // close if post
?>
<?php
// Query member data from the database and ready it for display
$sql = mysql_query("SELECT * FROM jobseeker_members WHERE id='$id' LIMIT 1");
while($row = mysql_fetch_array($sql)){
$fullname = $row["fullname"];
$contact = $row["contact"];
$qualific = $row["qualification"];
}
?>
<form action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data" name="form" id="form" onsubmit="return validate_form ( );">
<label>FullName:</label>
<input class="txtbox" name="fullname" type="text" id="fullname"
value="<?php echo "$fullname"?>"/>
<label>Contact No:</label>
<input class="txtbox"name="contact" type="text" id="contact" value="<?php echo "$contact"; ?>" /><br>
<label>Qualification :</label>
<select class="txtbox" name = "qualific">
<option value="<?php echo "$qualific"; ?>"><?php echo "$qualific"; ?></option>
<option value="Below SSC(10 Std)">Below SSC(10 Std)</option>
<option value="SSC(10 Std) passed">SSC(10 Std) passed</option>
<option value="HSC(12 Std) passed">HSC(12 Std) passed</option>
<option value="Graduate">Graduate</option>
<option value="Post Graduate">Post Graduate</option>
</select>
<input class="submitbtn" name="Submit" type="submit" value="Save" />
</form>
just using Multi Conditional IF
if($_POST['fullname'] == '')
{
//value
}
elseif($_POST['qualific'] == '')
{
//value
}
and so on ...
If you want to check the data is changing or not you can use session to hold data from database and campare with data from the form.
while($row = mysql_fetch_array($sql)){
$fullname = $row["fullname"];
// Place Session variable 'fullname'
$fullname = $_SESSION[$fullname];
$contact = $row["contact"];
// Place Session variable 'contact'
$contact = $_SESSION[$contact];
$qualific = $row["qualification"];
// Place Session variable 'qualification'
$qualific = $_SESSION[$qualific];
}
And Compare it :
if($_SESSION['fullname'] !== $_POST['fullname'])
{
// do something
} elseif($_SESSION['fullname'] !== $_POST['fullname']) {
// do something
}
and so on...
btw, sorry for my english

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.

change dropdown from array to check box

I would like a change from the drop down to the checkbox, I want to change it because I want firstly select the list in the array can be selected before store to database via the checkbox, so the dropdown script was as follows
<?php
session_start();
define('DEFAULT_SOURCE','Site_A');
define('DEFAULT_VALUE',100);
define('DEFAULT_STC','BGS');
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
if(isset($_GET['reset'])) {
unset($_SESSION['selected']);
header("Location: ".basename($_SERVER['PHP_SELF']));
exit();
}
?>
<form action="do.php" method="post">
<label for="amount">Amount:</label>
<input type="input" name="amount" id="amount" value="1">
<select name="from">
<?php
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
if((isset($_SESSION['selected']) && strcmp($_SESSION['selected'],$key) == 0) || (!isset($_SESSION['selected']) && strcmp(DEFAULT_STC,$key) == 0))
{
?>
<option value="<?php echo $key; ?>" selected="selected"><?php echo $stock; ?></option>
<?php
}
else
{
?>
<option value="<?php echo $key; ?>"><?php echo $stock; ?></option>
<?php
}
}
?>
</select>
<input type="submit" name="submit" value="Convert">
</form>
and i Changed it to the checkbox as follows
<?php
session_start();
define('DEFAULT_SOURCE','Site_A');
define('DEFAULT_VALUE',100);
define('DEFAULT_STC','BGS');
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
if(isset($_GET['reset'])) {
unset($_SESSION['selected']);
header("Location: ".basename($_SERVER['PHP_SELF']));
exit();
}
?>
<form action="do.php" method="post">
<label for="amount">Amount:</label>
<input type="input" name="amount" id="amount" value="1"><input type="submit" name="submit" value="Convert">
<?php
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
if((isset($_SESSION['selected']) && strcmp($_SESSION['selected'],$key) == 0) || (!isset($_SESSION['selected']) && strcmp(DEFAULT_STC,$key) == 0))
{
?>
<br><input type="checkbox" id="scb1" name="from[]" value="<?php echo $key; ?>" checked="checked"><?php echo $stock; ?>
<?php
}
else
{
?>
<br><input type="checkbox" id="scb1" name="from[]" value="<?php echo $key; ?>"><?php echo $stock; ?>
<?php
}
}
?>
</form>
but does not work, am I need to display Other codes related?
Thanks if some one help, and appreciated it
UPDATED:
ok post the first apparently less obvious, so I will add the problem of error
the error is
Fatal error: Call to undefined method st_exchange_conv::convert() in C:\xampp\htdocs\test\do.php on line 21
line 21 is $st->convert($from,$key,$date);
session_start();
if(isset($_POST['submit']))
{
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
$from = mysql_real_escape_string(stripslashes($_POST['from']));
$value = floatval($_POST['amount']);
$date = date('Y-m-d H:i:s');
$_SESSION['selected'] = $from;
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
$st->convert($from,$key,$date);
$stc_price = $st->price($value);
$stock = mysql_real_escape_string(stripslashes($stock));
$count = "SELECT * FROM oc_stock WHERE stock = '$key'";
$result = mysql_query($count) or die(mysql_error());
$sql = '';
if(mysql_num_rows($result) == 1)
{
$sql = "UPDATE oc_stock SET stock_title = '$stock', stc_val = '$stc_price', date_updated = '$date' WHERE stock = '$key'";
}
else
{
$sql = "INSERT INTO oc_stock(stock_id,stock_title,stock,decimal_place,stc_val,date_updated) VALUES ('','$stock','$key','2',$stc_price,'$date')";
}
$result = mysql_query($sql) or die(mysql_error().'<br />'.$sql);
}
header("Location: index.php");
exit();
}
Why I want to change it from dropdown to checkbox?
because with via checkbox list I will be able to choose which ones I checked it was the entrance to the database, then it seem not simple to me, I looking for some help< thanks So much For You mate.
You have not removed the opening <select> tag.
But you removed the <submit> button.
You changed the name from "from" to "from[]".
EDIT: After your additions:
Using the dropdown list you were only able to select one value for from. Now you changed it to checkboxes and thus are able to select multiple entries. This results in receiving an array from[] in your script in do.php. Your functions there are not able to handle arrays or multiple selections in any way.
You have to re-design do.php, change your form back to a dropdown list or use ratio buttons instead.

Categories