So I have some data in MySQL being shown on my PHP page inside a table. I've set it up so that each page only displays 3 results each (temporary until it goes live, then it will be more). Everything works fine and it displays those 3 results on each page just fine.
What I want to do is be able to change the amount of results on each page right from the main PHP page. I can change the amount shown on that one page, but as soon as I go to page 2, it resets to 3 results. How can I remember the number stored in the variable, and display it on every page? I tried using SESSIONS, but I couldn't get it to work. I'm still a beginner btw.
$item = $_REQUEST['item'];
if(isset($_REQUEST['item'])){
$limit=$item;
}
else{
$limit=3;
}
//A few lines down -->
<form action="<?php $_SERVER['REQUEST_URI']?>" method="post">
Items: <input type="text" name="item">
<input type="submit" name"go" value="Go">
</form>
You could add SESSION use this way:
$item = $_REQUEST['item'];
if(isset($_REQUEST['item'])){
$limit=$item;
$_SESSION['item_limit'] = $limit;
}
else{
// If we find a limit set in the session use that
if (!empty($_SESSION['item_limit']) {
$limit = $_SESSION['item_limit'];
}
else {
$limit=3;
}
}
If you don't need to remember the value the next time the user visits the page you can simply output the $limit as a value attribute for the "item" input.
Items: <input type="text" name="item" value="<?php echo $limit; ?>">
Related
I am trying to access different elements in an XML so I can edit them or add new ones from within a web page. I'm using PHP to loop through the parent tags and display in a select list then have submit button to POST the element selected - no issue.
I then use PHP to find all the names of the selected elements children, and display those names in another select list form. This displays the children in the list correctly however when I hit submit it displays correctly if I echo $_POST("Section") but clears the previous $_POST("Page").
I think this has something to do with using action="", but interestingly if I change one them to GET it works as intended. I actually want a 3rd step into lower children again, so cannot use that solution as a dodgy workaround.
I wont post XML as it has sensitive data in it and you can just trust I am stepping through that fine, it's the php clearing $_POST that is the big issue for me.
Please go easy - I literally learnt how to make a basic html webpage in april.
Tried a bunch of different form action including the .php it is on, and also
<?php echo $_SERVER['PHP_SELF']; ?>" >
As stated before - using one as GET and one POST seems to solve the issue
<?php
//pages processing and put into an array
$pages_array = array();
$xml = simplexml_load_file('XML/links.xml') or die ("Failed to load");
foreach($xml->page as $page){
array_push($pages_array, $page->name);
}
$pagecount = count($pages_array);
?>
<form name="page_select" method="POST" action="">
<select name="Page">
<?php
for ($i = 0; $i < $pagecount; $i++){
print '<option>'.$pages_array[$i].'</option><br>';
}
?>
</select>
<input type="Submit" name="edit_page" value="edit"/>
</form>
<br></br>
<?php
// save page selected into $pg and display page being edited
$pg = $_POST["Page"];
echo 'YOU ARE EDITTING PAGE: '.$pg;
?>
****** THEN FURTHER DOWN THE PAGE *****
<?php
// section processing
$section_array = array();
$xml = simplexml_load_file('XML/links.xml') or die ("Failed to load");
foreach($xml->page as $page){
if($page->name == $pg){
foreach($page->sections->section as $section){
array_push($section_array, $section->name);
}
}
}
$sectioncount = count($section_array);
?>
<form name="section_select" method="POST" action="">
<select name="Section">
<?php
for ($i = 0; $i < $sectioncount; $i++){
print '<option>'.$section_array[$i].'</option><br>';
}
?>
</select>
<input type="Submit" name="edit_section" value="edit"/>
</form>
<br></br>
<?php
$sct = $_POST["Section"];
echo 'YOU ARE EDITTING SECTION: '.$sct;
?>
I want output to remember both arrays after the second form is submitted, however due to the first POST variable being wiped it means I also lose the second array since when it gets back to pushing to $section_array $page->name can never = $pg since $pg is now empty
Every time you submit a form, the page is reloaded and PHP will only have access to the POST variables from the form that triggered the page reload. This means that as your second form is submitted, $_POST['Page'] ceases to exist.
There are many ways around this problem, here is a fairly simple one. In your second form, create a hidden input that contains the value of the $_POST['Page'] variable. That way, when the second form is submitted, the Page value will be propagated to the next step of the process. Adding this code to your section_select form should suffice:
<?php
if(isset($_POST['Page'])) {
?>
Page: <?php echo $_POST['Page'] ?>
<input type="hidden" name="Page" value="<?php $_POST['Page'] ?>" />
<?php
}
?>
I'm currently working on a personal content management system project, but I've run into a problem.
<ul>
<?php
if(!$result) { //Check for result
die("You have no pages ☹ Why not create one?");
} else {
while ($pages = mysqli_fetch_assoc($result)) { //Loop through results
?>
<li class="triple"><span><?php echo $pages["title"]?></span><span><?php echo $pages["visible"] ?><span /><form action = "editPage.php" method="post"><input type="submit" value="Edit Page" name="<?php $pages["title"];?>" /></form></li> //Create li elements for each result that gets created
<?php
};
};
?>
</ul>
Basically I'm using a query to results from a MySQL table and make a list of pages, the problem I've run into is that on the end form what I want to happen is I want a session variable to be stored saying which page is going to be edited, but I can't use $_POST in the form at the end to get the name because obviously the name is automatically generated from the table. Each person who uses it would have a different name for a page so I can't just get one name e.g. $_POST['homepage'].
If anyone can offer any advice on how to solve my problem or even how to come up with a better solution to store which page will be edited as it goes onto another page (editPage.php) that would be great.
Use $_SESSION[] to store the data for your $page arrays and access it again on editPage.php. You will need to make sure you call start_session(); on both pages though for it to work as expected. Since you're creating multiple forms and don't know which one will be submitted at the time PHP is running you would need to store all the pages in your $_SESSION and then iterate through them to check for the one which was selected in editPage.php:
$_SESSION['pages'] = array();
while ($page = mysqli_fetch_assoc($result)) {
$_SESSION['pages'][] = $page;
echo "<li class=\"triple\">
<span>".$page["title"]."</span>
<span>".$page["visible"]."</span>
<form action=\"editPage.php\" method=\"post\">
<input type=\"hidden\" name=\"pageID\" value=\"".$page['id']."\">
<input type=\"submit\" value=\"Edit Page\">
</form>
</li>";
}
Then in editPage.php
foreach($_SESSION['pages'] as $page){
if($page['id'] == $_POST['pageID']){ $editpage = $page; break; }
}
// do stuff with $editpage data
Another option would be to use serialize($page) and send the array with the form data in a hidden input element.
<input type='hidden' name='data' value='<?php echo serialize($page); ?>'>
Then you can use $editpage = unserialize($_POST['data']); to turn it back into an array in editPage.php.
This is my first post, so excuse me if I will not provide the information correctly.
So my problem is the following:
This is the first form:
<h1>Modificare carti</h1>
<br />
<form action="UTLcrt.php" method="post">
Cod Carte: <br /><input type="numeric" name="cod"><br>
Nume: <br /><input type="text" name="nume"><br>
Autor: <br /><input type="text" name="autor"><br>
Editura: <br /><input type="text" name="editura"><br>
Disponibilitate: <br /><input type="text" name="disp"><br>
Pret: <br /><input type="numeric" name="pret"><br>
<select name="vmod">
<option value="mod">Modificare carte</option>
<option value="str">Sterge carte</option>
<option value="src" >Cauta carte</option>
</select>
<input type="submit">
</form>
The UTLcrt.php contains the following code:
<?php
if (isset($_POST['vmod'])) {
$urls = array(
'mod' => 'modcrt.php',
'str' => 'strcrt.php',
'src' => 'srccrt.php'
);
$url = $urls[$_POST['vmod']];
header("Location: " . $url);
}
?>
And each php page does the following:
modcrt.php changes the entry in our database with the same"cod" with the info provided in the first form
strcrt.php deletes the register in our database, if the "cod" we entered in the first form finds a match
srccrt.php searches in the database if the register with the "cod" provided in the first form was found and shows a possitive message.
My problem is the following: the information I put in the first form doesn't get in the modcrt.php,strcrt.php,src.php pages... the $_Post's are empty...
How to send the information from the first page, trough the second and then to the third?
You can keep them in Session, by using
$_SESSION['info1']=$info1;
The POST values are empty because the third page isn't receiving a POST request. The order of events is this:
User requests the first page.
User POSTs a form to the second page, with values.
Second page tells the user to issue a GET request to the third page.
User requests the third page.
There are a few different ways to keep the information in the chain. You can:
Add it to the query string for the redirect
Store it in session
Store it in a database
etc.
The first one might look like this:
header("Location: " . $url . "?key=value");
Where the key/value pair is similar to those in a POST. In this case the values would be available to the third page in GET:
$_GET['key']
If you use session, the values stay server-side. So in the second page you can set the value:
$_SESSION['key'] = $value;
And then retrieve it in the third page:
$value = $_SESSION['key'];
Note that these session values will continue to live on the server until the session times out. You may want to unset them from the session once you're done with them if it starts to add confusion to other pages the user visits which also make use of these values.
Page 1
<?php
// this starts the session
session_start();
// this sets variables in the session
$_SESSION['color']='red';
$_SESSION['size']='small';
$_SESSION['shape']='round';
?>
Page 2
<?php
$color = $_SESSION['color'];
$size = $_SESSION['size'];
$shape = $_SESSION['shape'];
?>
and so on...
Is there any way to know if the page was refreshed or data was posted data on the same page?
To be little more specific:
I have to post data on the same page.
This affects the where condition of the query.
If the page was refreshed, then the where condition must be 1.
Otherwise, where condition contains some id to get specific data from
the table.
Your best bet is to use PHP sessions, along with your submitted data in $_POST. Let's presume for this example you have the following form:
<form action="this_page.php" method="post">
<input type="text" name="important-info" />
<input type="submit" value="Submit" />
</form>
Then elsewhere in the same page is the PHP code:
<?php
// example code
session_start();
if (!isset($_SESSION['previousVisitor']) && isset($_POST['important-info'])) {
// this is a new visitor who has submitted the form
$_SESSION['previousVisitor'] = true;
// where is based on $_POST['important-info']
} else () {
// where is 1
}
// close the session after you do what you need - this stops large pages causing hang
session_destroy();
Please note that they can clear this session variable by deleting their cookies.
on the top of the page just include
if(isset($_POST['name']) && $_POST['name']!=''){
//your code goes here
}
I suggest you to check request
//Here goes the code
session_start();
$counter = 0;
$counter = (isset($_SESSION['param'])) ? $counter++ : 0;
if($counter == 0)
echo "data GET or POST";
else
echo "refreshed";
** If you want only POST param, use $_POST instead of $_REQUEST
I want a function that prints those 2 "print" in the database ( insert intro ) when a button is pressed.
Here's the code:
<?php
$id2name=array();
$x=mysql_query("SELECT id,name FROM products WHERE id IN(".implode(',',array_keys($_SESSION['cart'])).")");
while($y=mysql_fetch_assoc($x)){
$id2name[$y['id']]=$y['name'];
}
foreach($_SESSION['cart'] as $k=>$v){
print "<br>[".$id2name[$k]."]\t".$v."\n <br>";
}
print "<br>$total<br>";
?>
How can I make that a function, to print it in the database when a button is pressed?
Not sure if I got you right, but as far as I understand, you want to write something to the database by pressing a button, right?
Well, to trigger an action by pressing a button, you need a form:
<form action="page_to_process_the_db_request.php" method="post">
<input type="hidden" value="<?php echo $total;?>" name="total" />
<input type="submit" value="Wirite to DB!" />
</form>
In this example, I assume you want to write the variable $total to DB.
So you post the data to the processing page (which also can be the same one you're on) and there, you look if there's something in the $_POST-array:
<?php
if(isset($_POST['total'])) {
mysql_query("UPDATE products SET total = ". $total); //or something like that
}
?>
Not sure though if this is what you're looking for...
//edit
referring to your comment, I guess you want to write the output of the loop to DB...
At first, you have to create an appropriate structure, like an array:
foreach($_SESSION['cart'] as $k=>$v){
$id2name[$k]['name'] = $v;
}
now you can turn the array into a simple string with
$serialized_array = serialize($id2name);
And now you can write this string to db. And when you read it from db, you can turn it back into an array again with:
$id2name_array = unserialize($serialized_array);