Edit page using php/mysql - php

I seem to be having problems with editing a users/members information. I have provided the scipt with the form below. Any solution to this is very much appreciated. I have taken out the validation checks to shorten the script.
The page renders with no errors. and the success message is being shown. However, information is not being changed/edited in the database.
Also the values from the database (corresponding to the 2nd db query being run) are being displayed in the fields of the form. However when i POST the changes the changes are not being made in the database.
**PHP scipt**
<?php
session_start();
if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
$username = $_SESSION['username'];
}
else {
echo "You have not signed in";
}
if (isset ($_POST['submit'])){
$title = $_POST['title'];
$content = $_POST['content'];
$make= $_POST['make'];
$model = $_POST['model'];
$price = $_POST['price'];
$location = $_POST['location'];
include_once "scripts/connect_to_mysql.php";
$title = mysql_real_escape_string($title);
$content = mysql_real_escape_string($content);
$make = mysql_real_escape_string($make);
$model = mysql_real_escape_string($model);
$price = mysql_real_escape_string($price);
$location = mysql_real_escape_string($location);
$title = eregi_replace("`", "", $title);
$content = eregi_replace("`", "", $content);
$make = eregi_replace("`", "", $make);
$model = eregi_replace("`", "", $model);
$price = eregi_replace("`", "", $price);
$location = eregi_replace("`", "", $location);
$sql = mysql_query ("UPDATE `advertisements` SET `title`='$title',
`content`='$content', `make`='$make', `model`= '$model', `price`='$price',
`location`='$location', `id`='$id' WHERE `advertisements` . `ads_id`='$ads_id'")
or die (mysql_error());
$success = "You have successfuly edited your ad";
}
else {
if (isset($_GET['ads_id'])) {
$ads_id = $_GET['ads_id'];
}
else {
echo "URL not found";
}
include_once "scripts/connect_to_mysql.php";
$query = mysql_query("SELECT * FROM advertisements WHERE ads_id='$ads_id'");
while($row = mysql_fetch_assoc($query))
{
$title = $row["title"];
$content = $row["content"];
$make = $row["make"];
$model = $row["model"];
$price = $row["price"];
$location = $row["location"];
$ads_id = $row ["ads_id"];
}
}
?>
**form**
<h1>Edit Advertisement</h1>
<?php echo "$success";?>
<form action="edit.php" method="POST" enctype="multipart/form-data">
Title: <input name="title" type="text" value="<?php print "$title"; ?>"/><br/>
Content: <input name="content" type="text" value="<?php print "$content";
?>"/><br/>
Make: <select name="make">
<option value="<?php echo "$make"; ?>"><?php echo "$make"; ?></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select> <br/>
Model: <select name="model">
<option value="<?php echo "$model"; ?>"><?php echo "$model"; ?></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select> <br/>
Price: <input name="price" type="text" value="<?php print "$price"; ?>"> <br/>
Location: <select name="location"> <br/>
<option value="<?php echo "$location"; ?>"><?php echo "$location";
?></option>
<option value="Leicester">Leicester</option>
<option value="Loughborough">Loughborough</option>
<option value="Nottingham">Nottingham</option>
<option value="Derby">Derby</option>
</select> <br/> <br/>
<input name="submit" type="submit" value="Edit ad"/>
</form>

try moving the
if (isset($_GET['ads_id'])) {
$ads_id = $_GET['ads_id'];
}
else {
echo "URL not found";
}
to the top right after the
if (isset ($_POST['submit'])){
this may cause problems
and your form action as i guess must have something like
<form action ="edit.php?ads_id=the id for the page" >

Related

Undefined index in php inside selected drop down

this is the undefined error that i got
the update is working. but after i clicked the submit button, the selected dropdown gave me this error.
$row=array();
if (isset($_GET['typeid'])) {
$sql = "SELECT * FROM vehicletype WHERE id_vehicleType=" . $_GET['typeid'];
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
}
// update record
if(isset($_POST['submit'])){
$id = mysqli_real_escape_string($link,$_POST['idtype']);
$type = mysqli_real_escape_string($link, $_POST['type']);
$status = mysqli_real_escape_string($link, $_POST['status']);
$update = mysqli_real_escape_string($link, $_SESSION['idinfostaf']);
$result = mysqli_query($link, "UPDATE vehicletype SET vehicle_Type='$type', status_vehicleType='$status', updateby_vehicleType='$update' WHERE id_vehicleType=".$id);
if ($result) {
$success = "Record updated successfully!";
}
else {
$error = "Error updating record...";
}
}
i put the php code and html on the same page..below is the html
<div class="form-group">
<label>Choose Vehicle Type Status</label>
<select class="form-control" name="status" required class="form-control" value="<?php if(isset($row['status_vehicleType'])){ echo $row['status_vehicleType'];} ?>">
<option value="">Select Vehicle Type</option>
<option
value="1" <?php if ($row['status_vehicleType']==$_GET["typeid"]) { echo 'selected="selected"' ;} ?> >Enabled</option>
<option
value="0" <?php if ($row['status_vehicleType']== $_GET["typeid"]) { echo 'selected="selected"' ;} ?> >Disabled</option>
</select>
<hr>
<button type="submit" name="submit" class="btn btn-info">Submit </button>
<span class="text-success"><?php if (isset($success)) { echo $success; } ?></span>
<span class="text-danger"><?php if (isset($error)) { echo $error; } ?></span>
i used the typeid to carry the values.
Try this:
<select value="<?php if(isset($row['status_vehicleType'])){ echo $row['status_vehicleType'];} ?>">
<option value="">Select Vehicle Type</option>
<option value="1" <?php
if(isset($row['status_vehicleBrand'])) {
if ($row['status_vehicleBrand']==$_GET["typeid"]) {
echo 'Selected' ;
}
} ?> >Enabled</option>
<option value="0" <?php
if(isset($row['status_vehicleBrand'])) {
if ($row['status_vehicleBrand']==$_GET["typeid"]) {
echo 'Selected' ;
}
} ?> >Disabled</option>
</select>

update query not working php

I'm working on a project and I'm suppose to update the another user's details using the $_GET method. My problem is that when user clicks on the id, it does go to edit page but when i change something and press the update button, it does not update. I'm not sure what am i doing wrong here.. I would really appreciate f someone can help me.
//Edit
My code is working now guys, I just changed the $_POST to $_REQUEST now and my form is updated.. Thank you all for helping me.. Thank you.. Here is my edited code.. I've taken out the oassword field, but i have a doubt.. Is using request safe?
<?php
include '../../connection.php';
$sid = $_REQUEST['sid'];
$query = "SELECT * FROM STUDENT WHERE STU_ID='$sid'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$unm = $row["STU_UNAME"];
$fnm = $row["STU_FNAME"];
$lnm = $row["STU_LNAME"];
$dob = $row["STU_DOB"];
$add = $row["STU_ADD"];
$tlp = $row["STU_PHONE"];
$sem = $row["STU_SEM"];
$img = $row["STU_IMG"];
$sts = $row["STU_STATUS"];
$cid = $row["CRS_ID"];
}
}
else{
$no = "0 result!";
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
//insert details in data
$sid = $_POST["sid"]; $snm = $_POST["snm"]; $fst = $_POST["fnm"]; $lst = $_POST["lnm"]; $sdb = $_POST["dob"];
$sad = $_POST["add"]; $shp = $_POST["tlp"]; $stt = $_POST["sts"]; $sem = $_POST["sem"]; $cid = $_POST["cid"];
$sql = "UPDATE STUDENT SET
STU_ID='$sid', STU_UNAME='$snm', STU_FNAME= '$fst', STU_LNAME='$lst', STU_DOB='$sdb', STU_ADD='$sad', STU_PHONE='$shp',
STU_STATUS='$stt', STU_SEM='$sem', CRS_ID = '$cid' WHERE STU_ID='$sid'";
//check if data is updated
if (mysqli_query($connection, $sql)) {
header("Location: searchStudent.php");
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
}
?>
Here's my form code:
<form class="contact_form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<ul>
<li>
<h2>Edit Students Details</h2>
<span class="required_notification">* Denotes Required Field</span>
</li>
<li>
<label for="id">Student ID: </label>
<input type="text" name="sid" value="<?php echo $sid;?>"/>
</li>
<li>
<label for="name">Username: </label>
<input type="text" name="snm" value="<?php echo $unm;?>"/>
</li>
<li>
<label for="name">First Name: </label>
<input type="text" name="fnm" value="<?php echo $fnm;?>"/>
</li>
<li>
<label for="name">Last Name: </label>
<input type="text" name="lnm" value="<?php echo $lnm;?>"/>
</li>
<li>
<label for="dob">Date of Birth: </label>
<input type="date" name="dob" value="<?php echo $dob;?>"/>
</li>
<li>
<label for="add">Address: </label>
<textarea name="add" rows="4" cols="50"><?php echo $add;?></textarea>
</li>
<li>
<label for="tlp">Phone: </label>
<input type="text" name="tlp" value="<?php echo $tlp;?>"/>
</li>
<li>
<label for="sts">Status: </label>
<select name="sts">
<option selected><?php echo $sts;?></option>
<option value="FULLTIME">FULL TIME</option>
<option value="PARTTIME">PART TIME</option>
</select>
</li>
<li>
<label for="sem">Semester: </label>
<select name="sem">
<option selected><?php echo $sem;?></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
</li>
<li>
<label for="crs">Course: </label>
<select name="cid">
<option selected><?php echo $cid;?></option>
<option value="AL">AL</option>
<option value="DBM">DBM</option>
<option value="DIT">DIT</option>
<option value="DTM">DTM</option>
<option value="FIS">FIS</option>
</select>
</li>
<li>
<button class="submit" type="submit" name="update">Update</button>
</li>
Make sure your form method is POST
Try this code:
<?php
include '../../connection.php';
//
$id = $_POST['id'];
$query = "SELECT * FROM STUDENT WHERE STU_ID='$id'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$unm = $row["STU_UNAME"];
$fnm = $row["STU_FNAME"];
$lnm = $row["STU_LNAME"];
$pwd = $row["STU_PWD"];
$dob = $row["STU_DOB"];
$add = $row["STU_ADD"];
$tlp = $row["STU_PHONE"];
$sem = $row["STU_SEM"];
$img = $row["STU_IMG"];
$sts = $row["STU_STATUS"];
$cid = $row["CRS_ID"];
}
}
else{
$no = "0 result!";
}
$pwdErr = $cpwdErr= "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if($_POST["pwd"] == $_POST["cpwd"]){
if(strlen($_POST["pwd"])>8){
//insert details in data
$sid = $_POST["sid"]; $pwd = $_POST["pwd"]; $snm = $_POST["snm"]; $fst = $_POST["fnm"]; $lst = $_POST["lnm"];
$sdb = $_POST["dob"]; $sad = $_POST["add"]; $shp = $_POST["tlp"]; $stt = $_POST["sts"]; $sem = $_POST["sem"];
$cid = $_POST["cid"];
$sql = "UPDATE STUDENT SET
STU_ID='$sid', STU_PWD='$pwd', STU_UNAME='$snm', STU_FNAME= '$fst', STU_LNAME='$lst', STU_DOB='$sdb', STU_ADD='$sad', STU_PHONE='$shp',
STU_STATUS='$stt', STU_SEM='$sem', CRS_ID = '$cid' WHERE STU_ID='$id'";
//check if data is updated
if (mysqli_query($connection, $sql)) {
header("Location: searchStudent.php");
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
}
else{
$pwdErr = "Invalid/Password must be more than 8 characters!";
}
}
else{
$cpwdErr = "Password not same!";
}
}
?>
Get ride for how to use prepare statement with example here.
Hope this help you well!
Your error is your are using POST in your form but getting its value with get change $_get with $_POST
$id = $_POST['id'];
well problem is that id you are posting is "sid" but you are using just "id" like $_POST['id'] instead of $_POST['sid']. so use this -
$id = $_POST['sid'];
instead of -
$id = $_POST['id']

Database does not get updated, But no error appears. MySQL and PHP

I'm making a website for a friend and basically I have 15 fields that are editable depending on the user type. Basically my code is echoing the row out on to the field, but when when I go to change it and update the database nothing happens. I don't receive any error messages, so i'm thinking it's something to do with my condition statements. My functions work fine, how ever my query doesn't seem to like me.
<?php
//end of function
}
// connect to the database
$server = 'localhost';
$user = 'root';
$pass = '';
$database = 'bubbles';
//Connect to the database
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
//Select the database name
$select = mysql_select_db($database) or die ("Could not connect to database ... \n" . mysql_error ());
// check if the form has been submitted. If it has, process the form and save it to the database
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
//Get form data to make sure it's valid
$id = $_POST["id"];
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$dueDate = mysql_real_escape_string(htmlspecialchars($_POST['dueDate']));
$numOfPages = mysql_real_escape_string(htmlspecialchars($_POST['numOfPages']));
$numOfCopies = mysql_real_escape_string(htmlspecialchars($_POST['numOfCopies']));
$paperSize = mysql_real_escape_string(htmlspecialchars($_POST['paperSize']));
$paperColor = mysql_real_escape_string(htmlspecialchars($_POST['paperColor']));
$weight = mysql_real_escape_string(htmlspecialchars($_POST['weight']));
$finishing = mysql_real_escape_string(htmlspecialchars($_POST['finishing']));
$paymentMethod = mysql_real_escape_string(htmlspecialchars($_POST['paymentMethod']));
$printColor = mysql_real_escape_string(htmlspecialchars($_POST['printColor']));
$status = mysql_real_escape_string(htmlspecialchars($_POST['status']));
$comment = mysql_real_escape_string(htmlspecialchars($_POST['comment']));
// check that firstname/lastname fields are both filled in
if ($name == '' || $dueDate == '' || $numOfPages == '' || $numOfCopies == '' || $comment == '')
{
// generate error message
$error = 'Please fill in all required fields!';
//error, display form
displayForm($id,
$name,
$dueDate,
$numOfPages,
$numOfCopies,
$paperSize,
$paperColor,
$weight,
$finishing,
$paymentMethod,
$printColor,
$comment,
$status,
$error);
}
else
{
//Insert form data into the database or die if there is an error
print $sql;
$sql = ("UPDATE orders SET `name` = '".$name."',
due_date = '".$dueDate."',
numOfPages = '".$numOfPages."',
numOfCopies = '".$numOfCopies."',
paper_size = '".$paperSize."',
paper_color = '".$paperColor."',
weight = '".$weight."',
finishing = '".$finishing."',
payment_method = '".$paymentMethod."',
color = '".$printColor."',
comments = '".$comment."',
`status` = '".$status."' WHERE id = '".$id."'");
$result = mysql_query($sql) or die (mysql_error());
// once saved, redirect back to the view page
header("Location: http://localhost/Bubbles/view-orders.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
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM orders 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
$id = $row['id'];
$name = $row['name'];
$dueDate = $row['due_date'];
$numOfPages = $row['numOfPages'];
$numOfCopies = $row['numOfCopies'];
$paperSize = $row['paper_size'];
$paperColor = $row['paper_color'];
$weight = $row['weight'];
$finishing = $row['finishing'];
$paymentMethod = $row['payment_method'];
$printColor = $row['color'];
$status = $row['status'];
$comment = $row['comments'];
// show form
displayForm($id,
$name,
$dueDate,
$numOfPages,
$numOfCopies,
$paperSize,
$paperColor,
$weight,
$finishing,
$paymentMethod,
$printColor,
$comment,
$status,
'');
}
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!';
}
}
?>
Updated with HTML
<html>
<head>
</head>
<body>
<form action"" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div class="floatLeft">
<p>Name: <br /> <input type="text" name="name" value="<?php echo $name; ?>"/></p>
<p>Due Date (ex: yyyy-mm-dd): <br /> <input type="datetime" name="dueDate" value="<?php echo $dueDate; ?>" /></p>
<p># of Pages <br /> <input type="number" name="numOfPages" value="<?php echo $numOfPages; ?>"/></p>
<p># of Copies <br /> <input type="number" name="numOfCopies" value="<?php echo $numOfCopies; ?>"/></p>
</div>
<div class="floatLeft">
<p>Paper Size<br />
<select name = "paperSize" value="<?php echo $paperSize; ?>">
<option value="8.5 x 11in">8.5 x 11 inches</option>
<option value="8.5 x 14in">8.5 x 14 inches</option>
<option value="11 x 17in">11 x 17 inches</option>
</select>
</p>
<p>Paper Color<br />
<select name = "paperColor" value="<?php echo $paperColor; ?>">
<option value = "pulsar pink">Pulsar Pink</option>
<option value = "fireball fuchsia">Fireball Fuchsia</option>
<option value = "plasma pink">Plasma Pink</option>
<option value = "re-entry red">Re-entry Red</option>
<option value = "rocket red">Rocket Red</option>
<option value = "cosmic orange">Cosmic Orange</option>
<option value = "galaxy gold">Galaxy Gold</option>
<option value = "solar yellow">Solar Yellow</option>
<option value = "venus violet">Venus Violet</option>
<option value = "planetary purple">Planetary Purple</option>
<option value = "celestial blue">Celestial Blue</option>
<option value = "lunar blue">Lunar Blue</option>
<option value = "gamma green">Gamma Green</option>
<option value = "martian green">Martian Green</option>
<option value = "terra green">Terra Green</option>
<option value = "lift-off lemmon">Lift-off Lemon</option>
</select>
</p>
<p>Weight<br/>
<select name = "weight" value="<?php echo $weight; ?>">
<option value="20lbs">20lbs</option>
<option value="60lbs">60lbs</option>
<option value="65lbs">65lbs</option>
</select>
</p>
<p>Finishing<br />
<select name = "finishing" value="<?php echo $finishing; ?>">
<option value="none">None</option>
<option value="cutting">Cutting</option>
<option value="folding">Folding</option>
<option value="quaters">Quaters</option>
<option value="binding">Bindings</option>
</select>
</p>
<p>Payment method<br />
<select name = "paymentMethod" value="<?php echo $paymentMethod; ?>">
<option value="Cash">Cash</option>
<option value="Credit">Credit</option>
<option value="Check">Check</option>
<option value="Wilscard">Wilscard</option>
</select>
</p>
<p>Print BW/C<br />
<select name = "printColor" value="<?php echo $printColor; ?>">
<option value="Black">Black</option>
<option value="White">White</option>
<option value="Color">Color</option>
</select>
</p>
</p>
</div>
<div class="floatLeft">
<p>Status<br />
<select name = "status" value="<?php echo $row['status']; ?>">
<option value="Recieved">Received</option>
<option value="In Progress">In Progress</option>
<option value="Completed">Completed</option>
</select>
<p>Comment (Cannot exceed 200 characters):<br />
<textarea name="comment" value="<?php echo $comment; ?>"></textarea><br />
</p>
<input type="submit" value="Edit Order" />
</div>
</body>
</html>
UPDATE: I fixed the code, thanks everyone for all the help, but my error was that when I check the empty field, there was nothing written in the comment box so it was thinking all fields were empty when in reality they weren't. i updated the field check with this code and it works fine now.
I updated the if statement from this:
if ($name == '' || $dueDate == '' || $numOfPages == '' || $numOfCopies == '' || $comment == '')
To this:
if ($name == '' || $dueDate == '' || $numOfPages == '' || $numOfCopies == '')
It doesn't look like you're running the query after you create it in the $sql variable. You'll want to execute the query like you do later in the code:
$result = mysql_query($sql) or die(mysql_error());
This will return true on success or false (and die) on failure.
If you execute your UPDATE sql statement should give you some ERROR (since you forgot SET). However, you are not executing it. Once you fix that issue, you need to change your UPDATE statement to
$sql = "UPDATE orders
SET
`name` = '".$name."',
due_date = '".$dueDate."',
numOfPages = '".$numOfPages."',
numOfCopies = '".$numOfCopies."',
paper_size = '".$paperSize."',
paper_color = '".$paperColor."',
weight = '".$weight."',
finishing = '".$finishing."',
payment_method = '".$paymentMethod."',
color = '".$printColor."',
comments = '".$comment."',
`status` = '".$status."'
WHERE
id = '".$id."'";
Reference: https://dev.mysql.com/doc/refman/5.0/en/update.html
Note: I escaped name and status columns since their are reserved words
Use this query it may solve your problem:
$sql = "UPDATE orders set name ='".$name."' set due_date = '".$dueDate."' set numOfPages = '".$numOfPages."' set numOfCopies = '".$numOfCopies."' set paper_size = '".$paperSize."' set paper_color = '".$paperColor."' set weight = '".$weight."' set finishing = '".$finishing."' set payment_method = '".$paymentMethod."' set color = '".$printColor."' set comments = '".$comment."' set status = '".$status."' WHERE id = '".$id."' ";

Populating select box with existing value

I have created a form which allows users to edit existing data within a database, I pull information from one page to the next to populate text boxes and select boxes. I have managed to populate the select box with the correct value but when the update statement goes through it deletes or doesn't recognize the pre-existing value. Can anyone help?
if (isset($_POST['submit'])) {
// Process the form
if (empty($errors)) {
$id = $brand["brandId"];
$brandName = mysql_prep($_POST["brandName"]);
$brandCategory = mysql_prep($_POST["brandCategory"]);
$brandKeyword = mysql_prep($_POST["brandKeyword"]);
$addedBy = mysql_prep($_SESSION['username']);
$query = "UPDATE brands SET ";
$query .= "brandName = '{$brandName}', ";
$query .= "brandCategory = '{$brandCategory}', ";
$query .= "brandKeyword = '{$brandKeyword}', ";
$query .= "addedBy = '{$addedBy}', ";
$query .= "dateTime = CURRENT_TIMESTAMP ";
$query .= "WHERE brandId = '{$id}' ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
// Success
$_SESSION["message"] = "Brand updated.";
redirect_to("search.php");
} else {
// Failure
$_SESSION["message"] = "Brand update failed.";
}
}
} else {
// This is probably a GET request
} // end: if (isset($_POST['submit']))
?>
<?php $layout_context = "user"; ?>
<?php include("../includes/layouts/header.php"); ?>
<?php include("../includes/layouts/navigation.php"); ?>
<div class="section">
<div id="message">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
</div>
<form id="edit_brands" action="edit_brands.php?id=<?php echo urlencode($brand["brandId"]); ?>" method="post">
<h2>Edit Brand Information: <?php echo htmlentities($brand["brandName"]);?></h2>
<p>
<label for="bname">Brand Name:</label>
<input class="textbox" id="bname" type="text" name="brandName" value="<?php echo htmlentities($brand["brandName"]); ?>" autofocus/>
</p>
<p>
<label for="bcategory">Brand Category:</label>
<select class="textbox" id="bcategory" type="text" name="brandCategory">
<option value=""><?php echo htmlentities($brand["brandCategory"]); ?></option>
<option value="Animation">Animation</option>
<option value="Automotive">Automotive</option>
<option value="Beauty and Fashion">Beauty & Fashion</option>
<option value="Comedy">Comedy</option>
<option value="Cooking and Health">Cooking & Health</option>
<option value="DIY">DIY</option>
<option value="Fashion">Fashion</option>
<option value="Film and Entertainment">Film & Entertainment</option>
<option value="Food and Drink">Food & Drink</option>
<option value="Gaming">Gaming</option>
<option value="Lifestyle">Lifestyle</option>
<option value="Music">Music</option>
<option value="News and Politics">News & Politics</option>
<option value="Science&Education">Science & Education</option>
<option value="Sports">Sports</option>
<option value="Technology">Technology</option>
<option value="Television">Television</option>
</select>
</p>
<p>
<label for="bkeyword">Brand Keyword:</label>
<textarea class="FormElement" id="bkeyword" name="brandKeyword" id="brandKeyword" placeholder=""><?php echo htmlentities($brand["brandKeyword"]); ?></textarea>
</p>
<p>
<input type="submit" class="button" name="submit" value="Edit Brand" onclick="return confirm('Do you wish to edit brand?');"/>
</p>
<p>
Cancel
</p>
</form>
</div>
</div>
The best way is to build the select from an array.
For instance:
<?php
$array = array('Animation', 'Automotive', 'Beauty and Fashion ', ...);
echo '<select class="textbox" id="bcategory" type="text" name="brandCategory">';
foreach ($array as $value){
if($value == htmlentities($brand["brandCategory"]){
echo '<option value='.$value.' selected>'.$value.'</option>';
}else{
echo '<option value='.$value.'>'.$value.'</option>';
}
}
echo '</select>;
This way you can check if the value in the array is the same that the one recieved by post and then add the selected attribute to the option tag.

Unnecessary Error Message Being Displayed

I've set up a form to update my blog and it was working fine up until about this morning. It keeps on turning up with an Invalid Entry ID error on the edit post page when I click the update button despite the fact that it updates the homepage.
All help is seriously appreciated.
<html>
<head>
<title>Ultan's Blog | New Post</title>
<link rel="stylesheet" href="css/editpost.css" type="text/css" />
</head>
<body>
<div class="new-form">
<div class="header">
</div>
<div class="form-bg">
<?php
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('tmlblog');
if (isset($_POST['update'])) {
$id = htmlspecialchars(strip_tags($_POST['id']));
$month = htmlspecialchars(strip_tags($_POST['month']));
$date = htmlspecialchars(strip_tags($_POST['date']));
$year = htmlspecialchars(strip_tags($_POST['year']));
$time = htmlspecialchars(strip_tags($_POST['time']));
$entry = $_POST['entry'];
$title = htmlspecialchars(strip_tags($_POST['title']));
if (isset($_POST['password'])) $password = htmlspecialchars(strip_tags($_POST['password']));
else $password = "";
$entry = nl2br($entry);
if (!get_magic_quotes_gpc()) {
$title = addslashes($title);
$entry = addslashes($entry);
}
$timestamp = strtotime ($month . " " . $date . " " . $year . " " . $time);
$result = mysql_query("UPDATE php_blog SET timestamp='$timestamp', title='$title', entry='$entry', password='$password' WHERE id='$id' LIMIT 1") or print ("Can't update entry.<br />" . mysql_error());
header("Location: post.php?id=" . $id);
}
if (isset($_POST['delete'])) {
$id = (int)$_POST['id'];
$result = mysql_query("DELETE FROM php_blog WHERE id='$id'") or print ("Can't delete entry.<br />" . mysql_error());
if ($result != false) {
print "The entry has been successfully deleted from the database.";
exit;
}
}
if (!isset($_GET['id']) || empty($_GET['id']) || !is_numeric($_GET['id'])) {
die("Invalid entry ID.");
}
else {
$id = (int)$_GET['id'];
}
$result = mysql_query ("SELECT * FROM php_blog WHERE id='$id'") or print ("Can't select entry.<br />" . $sql . "<br />" . mysql_error());
while ($row = mysql_fetch_array($result)) {
$old_timestamp = $row['timestamp'];
$old_title = stripslashes($row['title']);
$old_entry = stripslashes($row['entry']);
$old_password = $row['password'];
$old_title = str_replace('"','\'',$old_title);
$old_entry = str_replace('<br />', '', $old_entry);
$old_month = date("F",$old_timestamp);
$old_date = date("d",$old_timestamp);
$old_year = date("Y",$old_timestamp);
$old_time = date("H:i",$old_timestamp);
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p><input type="hidden" name="id" value="<?php echo $id; ?>" />
<strong><label for="month">Date (month, day, year):</label></strong>
<select name="month" id="month">
<option value="<?php echo $old_month; ?>"><?php echo $old_month; ?></option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<input type="text" name="date" id="date" size="2" value="<?php echo $old_date; ?>" />
<select name="year" id="year">
<option value="<?php echo $old_year; ?>"><?php echo $old_year; ?></option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
</select>
<strong><label for="time">Time:</label></strong> <input type="text" name="time" id="time" size="5" value="<?php echo $old_time; ?>" /></p>
<p><strong><label for="title">Title:</label></strong> <input type="text" name="title" id="title" value="<?php echo $old_title; ?>" size="40" /> </p>
<p><strong><label for="password">Password protect?</label></strong> <input type="checkbox" name="password" id="password" value="1"<?php if($old_password == 1) echo " checked=\"checked\""; ?> /></p>
<p><textarea cols="80" rows="20" name="entry" id="entry"><?php echo $old_entry; ?></textarea></p>
<p><input type="submit" name="update" id="update" value="Update"></p>
</form>
<p><strong>Be absolutely sure that this is the post that you wish to remove from the blog!</strong><br />
</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="id" id="id" value="<?php echo $id; ?>" />
<input type="submit" name="delete" id="delete" value="Delete" />
</form>
</div>
</div>
</div>
<div class="bottom"></div>
</body>
</html>
As far as I can see, you use either $_GET['id'] or $_POST['id'] to identify the entry ID. So you must check on the two when you set the $id variable:
if (!isset($_REQUEST['id']) || !is_numeric($_REQUEST['id']))
die("Invalid entry ID.");
Or, more selectively:
if (isset($_GET['id']) && is_numeric($_GET['id']))
$id = intval($_GET['id']);
else if (isset($_POST['id']) && is_numeric($_POST['id']))
$id = intval($_POST['id']);
else
die('Invalid entry ID.');
The empty check is redundant to is_numeric: an empty string is not numeric. Also, empty returns true with 0, which, I believe, should not halt your system since 0 could be a valid ID.
I believe the issue here is the mixing of POST and GET
Your form uses the POST method:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
So you need to change:
if (!isset($_GET['id']) || empty($_GET['id']) || !is_numeric($_GET['id'])) {
die("Invalid entry ID.");
}
else {
$id = (int)$_GET['id'];
}
to:
if (!isset($_POST['id']) || empty($_POST['id']) || !is_numeric($_POST['id'])) {
die("Invalid entry ID.");
}
else {
$id = (int)$_POST['id'];
}

Categories