PHP Update shows previous database entry's - php

I'm currently just coding around in my free time and follow up some random tutorials that other developers/coder's created in there spare time. Now I'm stuck with something very small. I have been trying to find a answer on the interwebz but I cant seem to find one, so here I'm hoping that someone is willing to read my PHP and HTML and see the error I created.
But before I share my code let me tell you what my problem is and what I try to achieve.
If you go to the following link "removed because problem is solved." and when you click on Home/About/Service/Random, you are able to edit one of these menu's. (title, posistion, visible). Now when I want to change the menu name "Home" to "Welcome" it correctly execute my SQL but for some reason, in the HTML Form it loads it's previous information. What I can do is copy the PHP and save it in a new php file and when clicking on submit it will change both menu/title/html form at the same time, but it wont show my succes and fail message anymore. I hope any of you understand what I'm trying to explain here and try to achieve. Now lets share the code.
PHP
<? find_selected_page(); ?>
<?
if (intval($_GET['info']) == 0){
redirect_to("content.php");
}
if(isset($_POST['submit'])){
$errors = array();
$required_fields = array('menu', 'position', 'visible');
foreach ($required_fields as $fieldname){
if (!isset($POST[$fieldname]) || (empty($_POST[$fieldname]) &&
!is_numeric($_POST[$fieldname]))) {
$errors [] = $fieldname;
}
}
$fields_with_lengths = array('menu' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength) {
if(strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength){
$errors[] = $fieldname;
}
}
$id = mysql_prep($_GET['info']);
$menu = mysql_prep($_POST['menu']); //use post array cuz we used post var to coll val in form
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
$query = "UPDATE information SET menu = '{$menu}', position = {$position}, visible = {$visible} WHERE id = {$id}";
$result = mysql_query($query, $connection);
if (mysql_affected_rows() == 1) {
$message = "The information was correctly updated.";
} else {
//failed
}
} else { //errors
}
?>
HTML
<? require_once ("includes/functions.php"); ?>
<? require_once ("includes/connect.php"); ?> //HERE IS MY CONNECTION TO MY DATABASE
///HERE IS MY PHP CODE
<? include ("includes/header.php"); ?>
<div id="content"> <!-- content here -->
<table id="table">
<tr>
<td id="nav">
<? echo navigation($sel_table1, $table2); ?>
</td>
<td id="main">
<h2>Edit Info <? echo $sel_table1['menu']; ?></h2>
<? if (!empty($message)) { echo "<p class=\"message\">" . $message . "</p>";} ?>
<form action="edit_info.php?info=<? echo urlencode($sel_table1['id']); ?>" method="post"/>
<p>Menu title
<input type="text" name="menu" value="<? echo ($sel_table1['menu']); ?>" id="menu">
</p>
<p>Position
<select name="position">
<?
$info_set = get_all_info();
$info_count = mysql_num_rows($info_set); //asks how many rows there are should be 3
for($count=1; $count <= $info_count+1; $count++){
echo "<option value='{$count}'";
if($sel_table1['position'] == $count){
echo "selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0"
<? if ($sel_table1['visible'] == 0){ echo "checked"; } ?>
/>No
<input type="radio" name="visible" value="1"
<? if ($sel_table1['visible'] == 1){ echo "checked"; } ?>
/>Yes
</p>
<input type="submit" name='submit' value="Edit information" />
</form> <br>
Cancel
</td>
</tr>
</table>
</div>
<? include ("includes/footer.php");?> //HERE I HAVE IF ISSET MYSQL CLOSE
And a more simple short version of the story is, I want to update the menu's with the success and failure message's without getting the old previous data in my HTML FORM
if needed for any reasons I have included the part of my functions.php where $sel_table and $table2 are staying.
function find_selected_page(){
global $sel_table1;
global $table2;
if (isset($_GET['info'])){
$sel_table1 = get_info_by_id($_GET['info']);
$sel_t2 = 0;
$table2 = NULL;
} else if (isset($_GET['page'])){
$table1 = 0;
$sel_table1 = NULL;
$table2 = get_pages_by_id($_GET['page']);
} else {
$table1 = NULL;
$sel_table1 = NULL;
$table2 = 0;
}
}
function navigation($sel_table1, $table2){
$output = "<ul class='info'>";
$info_set = get_all_info();
while ($info = mysql_fetch_array($info_set))
{
$output .= "<li"; if ($info["id"] == $sel_table1 ["id"]){
$output .= " class='selected'";
}
$output .= "><a href='edit_info.php?info=" . urlencode($info["id"]) . "'>{$info['menu']}</a></li>";
$page_set = get_pages_for_info($info["id"]);
$output .= "<ul class='pages'>";
while ($page = mysql_fetch_array($page_set))
{
$output .= "<li"; if ($page["id"] == $table2 ["id"]){
$output .= " class='selected'";
}
$output .= "><a href='content.php?page=" . urlencode($page["id"]) . "'>{$page['menu']}</a></li>"; }
$output .= "</ul>";
}
$output .= "</ul>";
return $output;
}

Related

Is my statement not updating because of the way I have it layed out?

This "page" is part of many that are all linked together using includes, but because I can't make it work I'm going straight to the url that relates to this exact page, and I still can't make it work, or figure out why.
What is supposed to happen, is the query checks if that stock is in the db, if it is, echo the values of the row, and if a submit button is pressed update the db based on the input values. If it's not in, echo the blank form, and if a submit button gets pressed insert into the db. I can't get either update or insert to work.
I'm going to post the entire page (minus the mysql connect,) so hopefully someone can spot an error.
<?php
$status = 'Active';
$stock = (isset($_GET['stock'])) ? $_GET['stock'] : '';
$cat = (isset($_GET['cat'])) ? $_GET['cat'] : '';
include ('../helper_content/title_data.php');
/* WHAT CATEGORY DO WE WANT? */
if($cat == "Sales") {
$table = "Titles";
if($stock) {$where = "stock = $stock";}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$status = $status;
$title_status = mysqli_real_escape_string($conn,$_POST['title_status']);
$title_number = mysqli_real_escape_string($conn,$_POST['title_number']);
$title_location = mysqli_real_escape_string($conn,$_POST['title_location']);
$title_owners = mysqli_real_escape_string($conn,$_POST['title_owners']);
$stock = $_GET['stock'];
}
}
/* Begin Main Query */
$sql5 = "SELECT * FROM `$table` WHERE $where";
$result5 = $conn->query($sql5);
if ($result5->num_rows > 0) {
// Stock exists, so submit will Update dB
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($update = $conn->prepare("UPDATE `Titles` SET status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?")){
$update->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
$update->execute();
};
if ($update->execute == TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating: " . $update->error;
}
}
// Display the HTML results
while($row5 = $result5->fetch_assoc()) {
echo "Found In Database";
// Title Number
$title_number = 'value="'.$row5['title_number'].'"';
$TitleStatus = $row5['title_status'];
$TitleLocation = $row5['title_location'];
$Owners = $row5['owners'];
}
} else {
// No Query Results Found
echo "Not Found In Database";
// Insert into dB
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($add = $conn->prepare("INSERT INTO `Titles` status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?")){
$add->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
$add->execute();
};
if ($add->execute == TRUE) {
echo "Record added into database";
} else {
echo "Error adding: " . $add->error;
}
}
/* End Main Query */
}
// Title Status
foreach($title_statuses as $title_status){
$selected = ($TitleStatus == $title_status) ? ' selected="selected"' : '';
$Title_status .= '<option value="'.$title_status.'"'.$selected.'>'.$title_status.'</option>';
}
// Title Location
foreach($title_locations as $title_location){
$selected = ($TitleLocation == $title_location) ? ' selected="selected"' : '';
$Title_location .= '<option value="'.$title_location.'"'.$selected.'>'.$title_location.'</option>';
}
// Prior Owners
foreach($prior_owners as $owners){
$selected = ($Owners == $owners) ? ' selected="selected"' : '';
$Owners_drop .= '<option value="'.$owners.'"'.$selected.'>'.$owners.'</option>';
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>?stock=<?php echo $stock; ?>">
<section class="title">
<h3>Title Info - Stock #:<?php echo $stock; ?></h3>
<p>
<label for="title_number" class="inline-edit">Title Num</label>
<input type="text" name="title_number" id="title_number" size="20" spellcheck="false" <?php echo $title_number; ?>>
</p>
<p>
<label for="title_status" class="inline-edit">Status</label>
<select name="title_status" id="title_status">
<option></option>
<?php echo $Title_status; ?>
</select>
</p>
<p>
<label for="title_location" class="inline-edit">Location</label>
<select name="title_location" id="title_location">
<option></option>
<?php echo $Title_location; ?>
</select>
</p>
<p>
<label for="title_owners" class="inline-edit">Owners</label>
<select name="title_owners" id="title_owners">
<option></option>
<?php echo $Owners_drop; ?>
</select> <a target="_blank" href="https://www.vehiclehistory.com/paging-vin-report-data/specifications.php?vin=<?php echo $vin; ?>"><i class="fa fa-history" aria-hidden="true" title="Vehicle History"></i></a>
</p>
</section>
<input type="submit" id="Submit" value="Submit">
</form>
I would start by organizing your code a little differently. You have one of two things that can be true: either the form was submitted (a POST request), or the page was requested via URL (a GET request). So, start with this:
<?php
# Data for dropdowns
include ('../helper_content/title_data.php');
$error = array();
$status = "Active";
$title_number = "";
$title_status = "";
$title_location = "";
$title_owners = "";
$vin = "";
# Was the form submitted via POST?
if(isset($_POST['Submit']))
{
# Yes
# Is this a new stock item?
if(empty($_POST['stock']))
{
# Yes - insert
/*
... get your variables from the $_POST array
*/
$title_number = filter_var($_POST['title_number'], FILTER_SANITIZE_STRING);
# ... repeat for other variables
if ($stmt = $conn->prepare("INSERT INTO `Titles` (`status`,`title_status`,`title_number`,`title_location`,`title_owners`) VALUES (?,?,?,?,?)"))
{
$stmt->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners);
if ($stmt->execute())
{
$stmt->close();
header('Location: ./?inserted=true');
exit();
}
else
{
$error[] = "Error adding: " . $stmt->error;
$stmt->close();
}
}
}
else
{
# No - update
$stock = $_POST['stock'];
/*
... get your variables from the $_POST array
*/
if ($stmt = $conn->prepare("UPDATE `Titles` SET status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?"))
{
$stmt->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
if ($stmt->execute())
{
$stmt->close();
header('Location: ./?updated=true');
exit();
}
else {
$error[] = "Error updating: " . $stmt->error;
$stmt->close();
}
}
}
}
else
{
# No - assume a GET
$status = 'Active';
$stock = $_GET['stock'];
$cat = $_GET['cat'];
if(isset($_GET['updated']))
{
$message = "Record updated";
}
else if(isset($_GET['inserted']))
{
$message = "Record added into database";
}
if($stock != "")
{
# Load the item?
$query = "SELECT * FROM `Sales` WHERE stock=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $stock);
if($stmt->execute())
{
$result = $stmt->get_result();
if($result)
{
$row = $result->fetch_assoc();
$title_number = $row['title_number'];
$title_status = $row['title_status'];
$title_location = $row['title_location'];
}
}
$stmt->close();
}
}
?>
<?php if(isset($message)) : ?>
<div class="alert alert-success">
<?= $message ?>
</div>
<?php endif; ?>
<?php if(isset($error)) : ?>
<div class="alert alert-danger">
<ul>
<?php foreach($error as $err): ?>
<li><?= $err ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<section class="title">
<h3>Title Info - Stock #:<?= $stock; ?></h3>
<input type="hidden" name="stock" value="<?= $stock; ?>" />
<p>
<label for="title_number" class="inline-edit">Title Num</label>
<input type="text" name="title_number" id="title_number" size="20" spellcheck="false" value="<?= $title_number; ?>" />
</p>
<p>
<label for="title_status" class="inline-edit">Status</label>
<select name="title_status" id="title_status">
<option></option>
<?php foreach($title_statuses as $option): ?>
<option <?= $option == $title_status) ? 'selected="selected"' : '' ?>><?= $option ?></li>
<?php endforeach; ?>
</select>
</p>
<p>
<label for="title_location" class="inline-edit">Location</label>
<select name="title_location" id="title_location">
<option></option>
<!-- Repeat the same process as $title_statuses -->
</select>
</p>
<p>
<label for="title_owners" class="inline-edit">Owners</label>
<select name="title_owners" id="title_owners">
<option></option>
<!-- Repeat the same process as $title_statuses -->
</select>
<a target="_blank" href="https://www.vehiclehistory.com/paging-vin-report-data/specifications.php?vin=$vin">
<i class="fa fa-history" aria-hidden="true" title="Vehicle History"></i>
</a>
</p>
</section>
<input type="submit" id="Submit" value="Submit" />
</form>
Here's a partial re-implementation of your page. I'm starting with the assumption that a stock number was part of the requesting URL, and looking that value up. I (for the moment) am ignoring loading the dropdown values in favor of getting a basic lookup to work.
You'll also notice I've switched to using shorttags in your markup - this is generally a more concise method of templating than sprinkling echos all over the place.
I've added a partial implementation of some save logic. You'll also notice that I added a hidden input to your form - you don't want to rely on a query string value when posting a form.
The code stores some simple error messages in an array, which gets echoed out if the insert or update fails. If successful, we redirect back to the same page with a simple flag variable, which we read on that request to know if we need to display an informational message. This is known as POST-REDIRECT-GET, and prevents users from accidentally (or purposefully) resubmitting the same form data over and over.

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.

Best Solution for this array

I am using checkboxes to query the database and I am struggling with this one, I am new to MySQL and PHP so sorry if this is simple!
Here is my code that I have...
<input type="checkbox" name="season2005" value="2005" <?php if(isset($_POST['season2005'])) echo "checked='checked'"; ?> > 2005-06
<input type="checkbox" name="season2006" value="2006" <?php if(isset($_POST['season2006'])) echo "checked='checked'"; ?> > 2006-07
<input type="checkbox" name="season2007" value="2007" <?php if(isset($_POST['season2007'])) echo "checked='checked'"; ?> > 2007-08
<input type="checkbox" name="season2008" value="2008" <?php if(isset($_POST['season2008'])) echo "checked='checked'"; ?> > 2008-09
<input type="checkbox" name="season2009" value="2009" <?php if(isset($_POST['season2009'])) echo "checked='checked'"; ?> > 2009-10
<input type="checkbox" name="season2010" value="2010" <?php if(isset($_POST['season2010'])) echo "checked='checked'"; ?> > 2010-11
<input type="checkbox" name="season2011" value="2011" <?php if(isset($_POST['season2011'])) echo "checked='checked'"; ?> > 2011-12
<input type="checkbox" name="season2012" value="2012" <?php if(isset($_POST['season2012'])) echo "checked='checked'"; ?> > 2012-13
<input type="checkbox" name="season2013" value="2013" <?php if(isset($_POST['season2013'])) echo "checked='checked'"; ?> > 2013-14
if (#$_POST['season2005'] == ""){ $season2005 = "0000"; } else { $season2005 = "2005"; }
if (#$_POST['season2006'] == ""){ $season2006 = "0000"; } else { $season2006 = "2006"; }
if (#$_POST['season2007'] == ""){ $season2007 = "0000"; } else { $season2007 = "2007"; }
if (#$_POST['season2008'] == ""){ $season2008 = "0000"; } else { $season2008 = "2008"; }
if (#$_POST['season2009'] == ""){ $season2009 = "0000"; } else { $season2009 = "2009"; }
if (#$_POST['season2010'] == ""){ $season2010 = "0000"; } else { $season2010 = "2010"; }
if (#$_POST['season2011'] == ""){ $season2011 = "0000"; } else { $season2011 = "2011"; }
if (#$_POST['season2012'] == ""){ $season2012 = "0000"; } else { $season2012 = "2012"; }
if (#$_POST['season2013'] == ""){ $season2013 = "0000"; } else { $season2013 = "2013"; }
$seasons = array($season2005,$season2006,$season2007,$season2008,$season2009,$season2010,$season2011,$season2012,$season2013);
$seasonpick = implode(",",$seasons);;
$matcharrays = array("AND season in ($seasonpick)");
At the moment all of the data is being queried to the database, so if nothing is selected them then part of query from this is "AND season in (0000,0000,0000,0000) etc
How would I go about only getting those selected into the array and if none are selected then the array would be blank.
Hope you understand what I mean!
Here is a working form with some checkboxes that will allow you to test and get the sql you intended.
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode(",", $dateArr);
$sql=".... and season in (".$dateSearch.")";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
echo "<input type=\"checkbox\" name=\"season[]\" value=\"".($i+2005)."\"> ".($i+2005);
}
?>
<input type="submit">
</form>
Output when 2009, 2010 and 2011 selected:
.... and season in (2009,2010,2011)
Okay, so how it works:
Checkboxes are best used when they all have the same name ending in a []. This makes it a nice array on it's own.
If post data is set, we then quickly throw an array unique over it (good habit for the most part in these types of queries) so that there are no duplicate values.
Then simply implode it into a string and pop it into the SQL query.
Edit: Added functionality to re-check checkboxes when submitted.
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode(",", $dateArr);
$sql=".... and season in (".$dateSearch.")";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
$chk="";
if(!empty($_POST['season']))
{
if(in_array($i+2005, $_POST['season']))
{
$chk=" checked=\"checked\" ";
}
}
echo "<input type=\"checkbox\" name=\"season[]\" ".$chk." value=\"".($i+2005)."\"> ".($i+2005);
}
?>
<input type="submit">
</form>
Edit 2: Just add quotes in the right places :)
<?php
$dateArr=array();
if(isset($_POST['season']))
{
$dateArr=array_unique($_POST['season']);
$dateSearch=implode("', '", $dateArr);
$sql=".... and season in ('".$dateSearch."')";
echo $sql;
}
?>
<html>
<form action="?" method="post">
<?php
for($i=0;$i<10;$i++)
{
$chk="";
if(!empty($_POST['season']))
{
if(in_array(($i+2005)."i", $_POST['season']))
{
$chk=" checked=\"checked\" ";
}
}
echo "<input type=\"checkbox\" name=\"season[]\" ".$chk." value=\"".(($i+2005)."i")."\"> ".($i+2005)."i";
}
?>
<input type="submit">
</form>
Edit 3: I feel like this is starting to really answer much more than one question :)
You can simply check the textbox to make sure it isn't empty and then append to a SQL string:
$sql="";
if(!empty($_POST['text1']))
{
$sql.=" and ftgf>= ".$_POST['text1']." ";
}
Having said that, I would strongly suggest that you NEVER allow the user to enter in parts of the actual SQL you will run - unless it is a closed/secure environment, which means NOT an ope website.
Insert the below code
$seasons = array($season2005,$season2006,$season2007,$season2008,$season2009,$season2010,$season2011,$season2012,$season2013);
//start
$seasons2 = array();
foreach ($seasons as $season)
{
if($season!=="0000")
{
array_push($seasons2,$season);
}
}
$seasonpick = implode(",",$seasons2);
//end

php session vars

I'm working on news archive page for my website, search over archive is done with start date, end date and news category as search parameters. Form values are stored in $_SESSION var, and then they are passed around as an array for pagination and other purposes.
My question would be how to prevent displaying search results on main archive search page if user for some reason goes again to it to make a new search.
here's the code
<?php
session_start();
if (isset($_POST['submit'])) {
//get data from the form
$archFld_1 = $_POST['archiveFld1'];
$archFld_2 = $_POST['archiveFld2'];
$archFld_3 = $_POST['archiveFld3'];
//just some check on fields
if (strlen($archFld_1) > 10) { $archFld_1 = ""; }
if (strlen($archFld_2) > 10) { $archFld_2 = ""; }
//save them as a array and store to session var
$_archValues = array($archFld_3, $archFld_1, $archFld_2);
$_SESSION['storeValues'] = $_archValues;
}
if (isset($_SESSION['storeValues'])) {
//check params for search
//set cat for query
if ($_SESSION['storeValues'][0] > 0) { $valCat = "AND newsCat=". $_SESSION['storeValues'][0] ." "; } else { $valCat = ""; }
//set date for query
if(($_SESSION['storeValues'][1] != "" ) && ($_SESSION['storeValues'][2] == "")) {
$DateStart = $_SESSION['storeValues'][1];
$valDate = " AND STR_TO_DATE(newsDate, '%d-%m-%Y') >= STR_TO_DATE('$DateStart', '%d-%m-%Y') ";
}
if(($_SESSION['storeValues'][2] != "") && ($_SESSION['storeValues'][1]=="")) {
$DateEnd = $_SESSION['storeValues'][2];
$valDate = " AND STR_TO_DATE(newsDate, '%d-%m-%Y') <= STR_TO_DATE('$DateEnd', '%d-%m-%Y') ";
}
if(($_SESSION['storeValues'][1]!="") && ($_SESSION['storeValues'][2] != "")) {
$DateStart = $_SESSION['storeValues'][1];
$DateEnd = $_SESSION['storeValues'][2];
$valDate = " AND STR_TO_DATE(newsDate, '%d-%m-%Y') BETWEEN STR_TO_DATE('$DateStart', '%d-%m-%Y') AND STR_TO_DATE('$DateEnd', '%d-%m-%Y') ";
}
//query string and stire it to session
$archQuery_string = $valCat.$valDate;
$_SESSION['storeQuery'] = $archQuery_string;
}
//pagination start
$page = $_GET['id'];
$perPage = 10;
$result = wbQuery("SELECT * FROM wb_news WHERE newsLang=1 ". $_SESSION["storeQuery"] ."ORDER BY newsId DESC");
$totalPages = mysql_num_rows($result);
if(!$page)
$page = 1;
$start = ($page - 1)*$perPage;
?>
<div id="sps_middle">
<div class="sps_cnt">
<div id="sps_middle_ly1">
<div class="sps_cnt_small">
<div class="sps_page_title"><h3><?php echo $wb_lng['txtArchiveTitle']; ?></h3></div>
<div class="sps_pages_cnt" style="padding-top: 10px; float: left; margin-bottom: 15px;">
<div class="sps_middle_col01">
<div style="float: left;">
<p>
<?php echo $wb_lng['txtArchiveInfo']; ?>
</p>
<form action="<?php $PHP_SELF; ?>" method="post" name="archiveForm" class="archiveForm">
<ul>
<li>
<input name="archiveFld1" type="text" id="archiveFld1" value="<?php echo $wb_lng['txtArhivaFld_01']; ?>" />
<input name="archiveFld2" type="text" id="archiveFld2" value="<?php echo $wb_lng['txtArhivaFld_02']; ?>" />
<select name="archiveFld3">
<option value="0"><?php echo $wb_lng['txtArhivaFld_07']; ?></option>
<option value="0" ><?php echo $wb_lng['txtArhivaFld_06']; ?></option>
<option value="1"><?php echo $wb_lng['txtArhivaFld_03']; ?></option>
<option value="2"><?php echo $wb_lng['txtArhivaFld_04']; ?></option>
<option value="3"><?php echo $wb_lng['txtArhivaFld_05']; ?></option>
</select>
</li>
<li style="float: right;">
<input name="reset" type="reset" class="sps_archiveform_btn" value="<?php echo $wb_lng['txtArchiveFormReset']; ?>"/>
<input name="submit" type="submit" class="sps_archiveform_btn" value="<?php echo $wb_lng['txtArchiveFormSend']; ?>"/>
</li>
</ul>
</form>
</div>
<hr />
<?php
if (#HERE GOES SOME CODE TO PERFORM THE CHECK!!!#) {
//perform db query
$result = wbQuery("SELECT * FROM wb_news WHERE newsLang=1 ". $_SESSION['storeQuery'] ."ORDER BY newsId DESC LIMIT $start, $perPage");
//count rows
$totalnews = mysql_num_rows($result);
$count = 1;
if($totalnews == 0) {
//no results, say to the user
echo "\t\t\t<div class=\"cil_news_text_big\">\n\t\t\t\t".$wb_lng['txtArchiveNoEntries']."\n\t\t\t</div>\n";
} else {
//we have results, yeeeeeeeeey
while($ROWnews = mysql_fetch_object($result)){
//set link extensions by the news cat
switch ($ROWnews->newsCat) {
case 1:
$newsCat_link = "news";
break;
case 2:
$newsCat_link = "statements";
break;
case 3:
$newsCat_link = "events";
break;
}
//text summary
if (strlen($ROWnews->newsShort) > 0 ) {$newsShortTxt = strip_tags($ROWnews->newsShort);
if ($lang_id==2) { $newsShortTxt = wbTranslit($newsShortTxt); }
} else {
$newsShortTxt = strip_tags($ROWnews->newsFull);
if ($lang_id==2) { $newsShortTxt = wbTranslit($newsShortTxt); }
}
$newsShortTxt = wbShorTxt($newsShortTxt, 210, "... <a title=\"".$wb_lng['txtShowMore']."\" href=\"http://".$_SERVER['HTTP_HOST']."/".$lang_link."/".$newsCat_link."/".$ROWnews->newsId."/full/\">".$wb_lng['txtShowMore']."...</a>");
//show news
echo "\t\t<div class=\"sps_news_list\">\n";
echo "\t\t<div class=\"sps_news_l\">\n";
echo "\t\t\t<img alt=\"\" src=\"http://".$_SERVER['HTTP_HOST']."/content/images/news/_thumb/".$ROWnews->newsImageThumb."\" />\n";
echo "\t\t</div>";
echo "\t\t<div class=\"sps_news_r\">\n";
//transliterate title
if ($lang_id==2) { $newsTitle = wbTranslit($ROWnews->newsTitle); } else { $newsTitle = $ROWnews->newsTitle; }
echo "\t\t\t<div class=\"sps_news_title\">\n\t\t\t\t<a title=\"".$newsTitle."\" href=\"http://".$_SERVER['HTTP_HOST']."/".$lang_link."/".$newsCat_link."/".$ROWnews->newsId."/full/\">".$newsTitle."</a>\n\t\t\t</div>\n";
echo "\t\t\t<div class=\"sps_news_date\">\n\t\t\t\t".$ROWnews->newsDate."\n\t\t\t</div>\n";
echo "\t\t\t<div class=\"sps_news_text_sh\">\n\t\t\t\t".$newsShortTxt."\n\t\t\t</div>\n";
echo "\t\t</div>";
echo "\t\t</div>";
//show <hr /> based on $count
if($totalnews != $count) { echo "\t\t\t<hr />\n"; }
$count++;
}
}
//pagination check
if($totalPages>$perPage) {
?>
<hr />
<div class="sps_pagginate">
<?PHP wbPageTurnFront($PHP_SELF."/".$lang_link."/archive/", $totalPages, $page, $perPage); ?>
</div>
<?php
}
}
?>
Any ideas?
Tnx :)
If user goes to make it a new search then you can clear the session at that time.
unset($_SESSION['storeValues']);

PHP form not processing

Hi there's a live version of the code below (taken from a tutorial) at my website below http://www.prupt.com/edit_subject.php
The page has a form that allows you to edit the subjects in the navigation bar down the left hand side. For example, you could click on "About Widget Corp" and the name "About Widget Corp" will appear in the subject text field, at which point your supposed to be able to edit it (i.e. change its name if you like) then click "edit subject" and it will update the new name in the navigation down the left hand side.
That's what it's supposed to do, according to the tutorial. However, if I try to edit one of the names, and then click "edit subject" it doesn't change anything. I'm guessing it's not updating the database and thereafter not outputting the correct/new data to the navigation bar
Do you see anything in the code below which would explain why it's not updating the navigation bar once I click "edit subject"?
<?php
//1.Create a database connection
$connection = mysql_connect("98.130.0.87", "username", "password");
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db("C263430_testorwallo" ,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
?>
<?php require_once("includes/functions.php"); ?>
<?php
if (intval($_GET['subj']) == 0) {
redirect_to("content.php");
}
if (isset($_POST['submit'])) {
$errors = array();
$required_fields = array('menu_name', 'position', 'visible');
foreach($required_fields as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] !=0)) {
$errors[] = $fieldname;
}
}
$fields_with_lengths = array('menu_name' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength ) {
if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) {
$errors[] = $fieldname; }
}
if (empty($errors)){
//Perform Update
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
$query = "UPDATE subjects SET
menu_name = '{$menu_name}',
position = {$position},
visible = {$visible}
WHERE id = {$id}";
$result = mysql_query($query, $connection);
if (mysql_affected_rows() == 1) {
//Success
} else {
//Failed
}
} else {
// Errors occurred
}
} //end: (isset($_POST['submit']))
?>
<?php find_selected_page();?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">
<h2>Edit Subject <?php echo $sel_subject ['menu_name'];?></h2>
<form action="edit_subject.php?subj=<?php echo urlencode($sel_subject['id']);?>" method="post">
<p>Subject name: <input type="text" name="menu_name" value="<?php echo $sel_subject['menu_name']; ?>" id="menu_name" /></p>
<p>Position:
<select name="position">
<?php
$subject_set = get_all_subjects();
$subject_count = mysql_num_rows($subject_set);
//$subject_count +1 because we are adding a subject
for($count=1; $count <= $subject_count+1; $count++) {
echo "<option value=\"{$count}\"";
if ($sel_subject['position'] == $count) {
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0"<?php
if ($sel_subject['visible'] == 0) { echo " checked";}
?>/>No
<input type="radio" name="visible" value="1"<?php
if ($sel_subject['visible'] == 1) { echo " checked"; }
?>/> Yes
</p>
<input type="submit" name"submit" value="Edit Subject"/>
</form>
<br/>
Cancel
</td>
</tr>
</table>
<?php include("includes/footer.php"); ?>
<?php
//5. Close connection
mysql_close($connection);
?>
Ok, saw the page code and it's likely that (see comment above).
<input type="submit" name"submit" value="Edit Subject"/>
You forgot the = sign, correct it to name="submit". That's why it doesn't see the form as submitted (if $_POST['submit']...)

Categories