Unnecessary Error Message Being Displayed - php

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'];
}

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>

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']

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.

Update MySQL record on a page created with GET url ID

I am creating a simple reporting system and I want the menues and pages to be generated from the database.
I saw this video on YouTube and managed to create a menu with the following code.
I have a database table called Reports and columns called rep_id, rep_date, rep_ledit_date, rep_by, department, position, report, and rep_to. And another table called users with columns called id, username, password, first_name, last_name, department, postion, and passphrase.
I managed to select the an added record for the reports table, however, I have the following problems.
1. The rep_to doesn't preselect the already chosen option
2. The record cannot be updated with php Notice: Undefined index: rep_id in C:\wamp\www\cme\edit-this-report.php on line 232 and no update on the database. This line is where report table is selected
Please see the php code below.
<?php
if(isset($_SESSION['users'])) {
$uname = $_SESSION['users'];
$fname = $_SESSION['firstname'];
$lname = $_SESSION['lastname'];
$dep = $_SESSION['depart'];
$pos = $_SESSION['position'];
$query = mysqli_query($con, "SELECT * FROM users WHERE username = $uname");
while($row = mysqli_fetch_assoc($query)) {
$id=$row['id'];
$fname=$row['first_name'];
$lname=$row['last_name'];
$dep = $row['department'];
$pos = $row['position'];
$repby = $row['first_name'] . " " . $row['last_name'];
$repdep = $row['department'];
$reppos = $row['position'];
}
}
mysqli_select_db($con, $db_name);
$edit= "SELECT * FROM reports WHERE rep_id = '{$_GET['rep_id']}'";
$result = mysqli_query($con, $edit) or die(mysqli_error($con));
$row2 = mysqli_fetch_array($result);
if(isset($_POST['update'])) {
$_GET['rep_id']=$row2['rep_id'];
$reptype = $_POST['reporttype'];
$report = $_POST['report'];
$repto = $_POST['reportedto'];
$update=(mysqli_select_db($con, $db_name));
if(!$update) {
die('Could not connect: ' . mysql_error($con));
}
else {
$sql = "UPDATE reports SET rep_type='$reptype', report='$report', rep_to='$repto',
rep_ledit_date=NOW() WHERE rep_id='{$_GET['rep_id']}'";
$retval = mysqli_query($con, $sql);
if(!$retval ) {
$errorMessage='Could not update data: ' . mysqli_error($con);
}
else {
$success="Updated data successfully\n";
header("location:edit-this-report.php");
mysqli_close($con);
}
}
}
?>
And the form code:
<form name="editor" action="edit-this-report.php" method="post" >
<p class="inline">
<span>
<label for="mem">Reported by</label>
<input type="text" name="reportedby" maxlength="20" disabled value="<?php print $fname . " " . $lname; ?>" />
</span>
</p>
<p class="inline">
<span>
<label for="mem">Department Name</label><input type="text" name="repdepart" disabled size="100" maxlength="100" value="<?php print $dep; ?>">
</span>
</p>
<p class="inline">
<span>
<label for="mem">Position</label><input disabled type="text" name="repposition" size="100" value="<?php print $pos; ?>">
</span>
</p>
<p>
<span>
<label for="mem">Report Type</label>
<select name="reporttype">
<option value=""<?php if ($row2['rep_type'] === 'Daily Report') echo ' selected="selected"'; ?>>Daily Report</option>
<option value=""<?php if ($row2['rep_type'] === 'Weekly Report') echo ' selected="selected"'; ?>>Weekly Report</option>
<option value=""<?php if ($row2['rep_type'] === 'Monthly Report') echo ' selected="selected"'; ?>>Monthly Report</option>
<option value=""<?php if ($row2['rep_type'] === 'Quarterly Report') echo ' selected="selected"'; ?>>Quarterly Report</option>
<option value=""<?php if ($row2['rep_type'] === 'Annual Report') echo ' selected="selected"'; ?>>Annual Report</option>
<option value=""<?php if ($row2['rep_type'] === 'Terminal Report') echo ' selected="selected"'; ?>>Terminal Report</option>
</select>
<span>
</p>
<p>
<span>
<label for="mem">Report</label>
<textarea name="report" id="report" rows="23" cols="auto" ><?php echo $row2['report'];?></textarea>
<span>
</p>
<p>
<span>
<label for="mem">Reported to</label>
<select name="reportedto">
<?php
require ("includes/db.php");
$q2= "SELECT * FROM users WHERE department like '%$repdep%'";
$result3=mysqli_query($con, $q2) or die(mysqli_error($con));
while ($getuser=mysqli_fetch_array($result3)){
$repto=$getuser['first_name'] . " " . $getuser['last_name'];
?>
<option value="<?php echo $repto; ?>"><?php echo $repto; ?></option>;
<?php
}
?>
</select>
</span>
</p>
<span>
<input name="update" type="submit" class="btn btn-large btn-primary" id="report_button" value="Submit Report" >
<input name="cancel" type="reset" class="btn btn-large btn-secondary" id="report_button" value="Cancel All Changes" >
</span>
</p>
</form>
Please help me on this.
Thanks!
I don't see a rep_id variable set in your form, so you're not getting back that value when submitting the form. You're relying on $_GET['rep_id'] in the previous query to provide the rep_id for your UPDATE, but I see no $_GET vars provided in your form. (Maybe not best practice to mix POST and GET, better yet add a hidden form var and set it to rep_id, and capture that as a POST var.)
None the less, the easiest way I can think of to make your code work is to append the rep_id to the form action attribute:
<form name="editor" action="edit-this-report.php?rep_id=<?php echo $_GET['rep_id']; ?>" method="post" >
Run that and report back if you get any more errors.
Another problem, though maybe not a show-stopper, before that in the SELECT * FROM users query, the $uname var is not quoted. Bigger, future problem though is using insecure, user-provided or hacker-manipulable variables in your SQL statements leaves your database open to sql-injection attacks.
UPDATE:
Consider something like this:
<?php
session_start();
require ('includes/db.php'); // provides $con, select database
// get logon info
if ( !isset($_SESSION['username']) ) { header('Location: logon.php'); } // logon and set session vars
else {
list($uname, $repby, $dep, $pos) =
array($_SESSION['username'], $_SESSION['repby'], $_SESSION['department'], $_SESSION['position']);
}
// get report id if GET'd
if ( isset($_GET['rep_id']) ) {
$rep_id = $_GET['rep_id'];
}
// update report if POST'd
else if ( isset($_POST['update'] ) ) {
$rep_id = $_POST['rep_id'];
$reptype = $_POST['reporttype'];
$report = $_POST['report'];
$repto = $_POST['reportedto'];
if ( mysqli_stmt_prepare($stmt, 'UPDATE reports SET rep_type= ?, report= ?, rep_to= ?, rep_ledit_date= ? WHERE rep_id= ?') ) {
mysqli_stmt_bind_param($stmt, 'sssi', $reptype, $report, $repto, NOW(), $rep_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
else { $errorMessage='Could not update report data: ' . mysqli_error($con); }
}
else { die('no report id'); }
// get/verify report info (can be moved to get'd if to save a db call when post'd)
list($rep_type, $report) = array('', '');
$stmt = mysqli_stmt_init($con);
if ( mysqli_stmt_prepare($stmt, 'SELECT rep_id, rep_type, report FROM Reports WHERE rep_id = ?') ) {
mysqli_stmt_bind_param($stmt, 'i', $rep_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $rep_id, $rep_type, $report);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
else { $errorMessage='Could not select report data: ' . mysqli_error($con); }
?>
<form name="editor" action="edit-this-report.php" method="post" >
<input type="hidden" name="rep_id" value="<?=$rep_id?>">
<p class="inline">
<span>
<label for="mem">Reported by</label>
<input type="text" name="reportedby" maxlength="20" disabled value="<?=$repby?>" />
</span>
</p>
<p class="inline">
<span>
<label for="mem">Department Name</label><input type="text" name="repdepart" disabled size="100" maxlength="100" value="<?=$dep?>">
</span>
</p>
<p class="inline">
<span>
<label for="mem">Position</label><input disabled type="text" name="repposition" size="100" value="<?=$pos?>">
</span>
</p>
<p>
<span>
<label for="mem">Report Type</label>
<select name="reporttype">
<?php
list($rep_type_da, $rep_type_we, $rep_type_mo, $rep_type_qu, $rep_type_an, $rep_type_te) = array('', '', '', '', '', '');
switch ( $rep_type ) {
case 'Daily Report': $rep_type_da = ' selected'; break;
case 'Daily Report': $rep_type_we = ' selected'; break;
case 'Daily Report': $rep_type_mo = ' selected'; break;
case 'Daily Report': $rep_type_qu = ' selected'; break;
case 'Daily Report': $rep_type_an = ' selected'; break;
case 'Daily Report': $rep_type_te = ' selected'; break;
}
?>
<option value="Daily Report" <?=$rep_type_da?>>Daily Report</option>
<option value="Weekly Report" <?=$rep_type_we?>>Weekly Report</option>
<option value="Monthly Report" <?=$rep_type_mo?>>Monthly Report</option>
<option value="Quarterly Report"<?=$rep_type_qu?>>Quarterly Report</option>
<option value="Annual Report" <?=$rep_type_an?>>Annual Report</option>
<option value="Terminal Report" <?=$rep_type_te?>>Terminal Report</option>
</select>
<span>
</p>
<p>
<span>
<label for="mem">Report</label>
<textarea name="report" id="report" rows="23" cols="auto" ><?=$report?></textarea>
<span>
</p>
<p>
<span>
<label for="mem">Reported to</label>
<select name="reportedto">
<option value=""></option>
<?php
if ( mysqli_stmt_prepare($stmt, 'SELECT CONCAT(first_name, last_name) AS repto FROM users WHERE department LIKE ?') ) {
mysqli_stmt_bind_param($stmt, 's', "%$dep%");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $repto);
while ( mysqli_stmt_fetch($stmt) ) {
echo '<option value="' . $repto . '">' . $repto . "</option>\n";
}
mysqli_stmt_close($stmt);
}
else { $errorMessage='Could not select dep user data: ' . mysqli_error($con); }
?>
</select>
</span>
</p>
<span>
<input name="update" type="submit" class="btn btn-large btn-primary" id="report_button" value="Submit Report" >
<input name="cancel" type="reset" class="btn btn-large btn-secondary" id="report_button" value="Cancel All Changes" >
</span>
</p>
</form>
I've not set up the database so I've not tested it. If you run this and get errors, post them in the comments.
You would have to identify exactly which line above is line 232, but an "Undefined Index" error in PHP means that you have an array ($_GET and $_POST are both arrays) and you are trying to access a value (In this case, the one: $_GET['rep_id'] = 1;) but it can't find the 'index' in the array (in this case 'rep_id').
Somewhere you are accessing an array element via index that has not yet been defined on the page.
EDIT:
Probably here:
$edit= "SELECT * FROM reports WHERE rep_id = '{$_GET['rep_id']}'";
$_GET is referencing a url variable called rep_id, but aren't you using post to send the rep_id? in this case try changing
$_GET['rep_id']
to
$_POST['rep_id']
In addition to the solution given by bloodyKnuckles, I also got a help from a friend.
There is also a problem in giving initial values to the post values below if(isset($_POST['update'])).
<?php
if(isset($_SESSION['users'])) {
$uname = $_SESSION['users'];
$fname = $_SESSION['firstname'];
$lname = $_SESSION['lastname'];
$dep = $_SESSION['depart'];
$pos = $_SESSION['position'];
$query = mysqli_query($con, "SELECT * FROM users WHERE username = $uname");
while($row = mysqli_fetch_assoc($query)) {
$id=$row['id'];
$fname=$row['first_name'];
$lname=$row['last_name'];
$dep = $row['department'];
$pos = $row['position'];
$repby = $row['first_name'] . " " . $row['last_name'];
$repdep = $row['department'];
$reppos = $row['position'];
}
}
mysqli_select_db($con, $db_name);
$edit= "SELECT * FROM reports WHERE rep_id = '{$_GET['rep_id']}'";
$result = mysqli_query($con, $edit) or die(mysqli_error($con));
$row2 = mysqli_fetch_array($result);
if(isset($_POST['update'])) {
$repid = $_POST['repid'];
$reporttype = $_POST['reporttype'];
$report = $_POST['report'];
$repto = $_POST['reportedto'];
$sql = "UPDATE reports SET rep_type='$reporttype', report='$report', rep_to='$repto', rep_ledit_date=NOW() WHERE rep_id='$repid'";
$retval = mysqli_query($con, $sql);
mysqli_close($con);
$success="You have successfully edited your report.";
}
?>
Then on the form, the values for reptype were not set. I also added a hidden field which retrieves the rep_id.
<form name="editor" action="edit-this-report.php?rep_id=<?php echo $_GET['rep_id']; ?>" method="post" >
<p class="inline">
<span>
<label for="mem">Reported by</label>
<input type="text" name="reportedby" maxlength="20" disabled value="<?php print $fname . " " . $lname; ?>" />
</span>
</p>
<p class="inline">
<span>
<label for="mem">Department Name</label><input type="text" name="repdepart" disabled size="100" maxlength="100" value="<?php print $dep; ?>">
</span>
</p>
<p class="inline">
<span>
<label for="mem">Position</label><input disabled type="text" name="repposition" size="100" value="<?php print $pos; ?>">
</span>
</p>
<input name="repid" type="hidden" id="repid" value="<?php echo $row2['rep_id']; ?>">
<p>
<span>
<select name="reporttype">
<option value="Daily Report"<?php if ($row2['rep_type'] === 'Daily Report') echo ' selected="selected"'; ?>>Daily Report</option>
<option value="Weekly Report"<?php if ($row2['rep_type'] === 'Weekly Report') echo ' selected="selected"'; ?>>Weekly Report</option>
<option value="Monthly Report"<?php if ($row2['rep_type'] === 'Monthly Report') echo ' selected="selected"'; ?>>Monthly Report</option>
<option value="Quarterly Report"<?php if ($row2['rep_type'] === 'Quarterly Report') echo ' selected="selected"'; ?>>Quarterly Report</option>
<option value="Annual Report"<?php if ($row2['rep_type'] === 'Annual Report') echo ' selected="selected"'; ?>>Annual Report</option>
<option value="Terminal Report"<?php if ($row2['rep_type'] === 'Terminal Report') echo ' selected="selected"'; ?>>Terminal Report</option>
</select>
<span>
</p>
<p>
<span>
<label for="mem">Report</label>
<textarea name="report" id="report" rows="23" cols="auto"><?php echo $row2['report'];?></textarea>
<span>
</p>
<p>
<span>
<label for="mem">Reported to</label>
<select name="reportedto">
<?php
require ("includes/db.php");
$q2= "SELECT * FROM users WHERE department like '%$repdep%'";
$result3=mysqli_query($con, $q2) or die(mysqli_error($con));
while ($getuser=mysqli_fetch_array($result3)){
$repto=$getuser['first_name'] . " " . $getuser['last_name'];
?>
<option value="<?php echo $repto; ?>"><?php echo $repto; ?></option>;
<?php
}
?>
</select>
</span>
</p>
<span>
<input name="update" type="submit" class="btn btn-large btn-primary" id="report_button" value="Submit Report" >
<input name="cancel" type="reset" class="btn btn-large btn-secondary" id="report_button" value="Cancel All Changes" >
</span>
</form>
</p>
I hope this helps other visitors. Thank you bloodyKnuckles and Mark for the help!

Edit page using php/mysql

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" >

Categories