Keeping array from POST when using pagination link - php

I am having a litte issue with my searchengine.
It outputs the searchresult just fine, but when I am clicking a pagination link it fails, of course because it no longer have the $_POST array. I am using this piece of code:
if(empty($_POST) == false) {
$res = $search->search_ads($_POST);
if($res == false) {
$view->setData('numres', 0);
} else {
$view->setData('numres',$res[2]);
$view->setData('adverts', $res[0]);
}
$app->view()->setData('paginate', $res[1]);
$app->render('search.tpl');
} else {
$app->render('404.tpl');
}
When I click on f.x. "Page 2" it will render the 404 template.
Is there a way I can keep the $_POST array and reuse it in the search_ads function?
"paginate" contains the HTML for the pagination
<li><a class=\"paginate\" href=\"$target?page=$next_page&ipp=$this->items_per_page\">«</a></li>":"<li><span class=\"inactive\" href=\"#\">«</span></li>

use sessions.
session_start(); //on the top of your php file.
...
if(!empty($_POST))
$_SESSION['post_data']= $_POST;
...
if(empty($_SESSION['post_data']) == false) {
$res = $search->search_ads($_SESSION['post_data']);
...
}

Store the post array in a variable and use that elsewhere?
$post_array = $_POST;
$res = $search->search_ads($post_array);

You want to check for $_GET rather than $_POST on subsequent pages, as that's the method your using to pass the data:
href=\"$target?page=$next_page&ipp=$this->items_per_page\"
Will provide you with a $_GET array containing key value pairs:
$_GET['page'] = value of $next_page
$_GET['ipp'] = value of $this->items_per_page

Related

PHP => $_SESSION Array only keeps last variable

I'm building an interface for an online shop, where every item is a FORM and the BUY button is a submit,it submits the name and price of the clicked form and that data is displayed on a CONFIRM ORDER page. On that confirm order page I've created an array as follows
if (!isset($input_order_arr)) {
$input_order_arr = array();
}
After that I fetch the posted variables and push them into the array
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['item-title']) && !empty($_POST['item-price'])) {
$item_title = test_input($_POST['item-title']);
$item_price = test_input($_POST['item-price']);
array_push($input_order_arr,$item_title,$item_price);
}
}
$_SESSION['chosen_item'] = $input_order_arr;
*NOTE : test_input is a function that does striplashes , htmlspecialchars and htmltrim, for security purposes. (someone might edit the value of the item via the Chrome developer console? not sure if that holds any threat though)
And after that the value is displayed in a table like so
<?php if (isset($_SESSION['chosen_item'])) {
foreach ($_SESSION['chosen_item'] as $value) {
echo "<td>" . $value . "</td>";
}
} ?>
And here comes the problem.
If you order an item its price and name are displayed, but if u go back and you order another item, the previous item and its price are lost, as if its not adding new lines to the array,but replacing the old ones, or the session only saves data from one action, which wouldn't make any sense, since thats what $_SESSION is about, the code is presented with session_start(); in every page that is using the $_SESSION variable.
Main Question - Why could it be that the $_SESSION Array is losing its older inputs?
You could push directly into the session like this
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['item-title']) && !empty($_POST['item-price'])) {
array_push($_SESSION['chosen_item'],
test_input($_POST['item-title']),
test_input($_POST['item-price'])
);
}
}
//$_SESSION['chosen_item'] = $input_order_arr;
Or as your test_input() is likely doing nothing useful
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['item-title']) && !empty($_POST['item-price'])) {
array_push($_SESSION['chosen_item'],
$_POST['item-title'],
$_POST['item-price']
);
}
}
You might find this data easier to use later by doing
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['item-title']) && !empty($_POST['item-price'])) {
array_push($_SESSION['chosen_item'],
array('title' => $_POST['item-title'],
'price' => $_POST['item-price']
)
);
}
}
you need $_SESSION['chosen_item'][]=$input_order_arr; your overwriting the same index instead of creating new one
$_SESSION['chosen_item'][]=$input_order_arr;
Note : And also it should be moved inside the if statement .to avoid empty array storing in session
When you go back, you basically are setting the chosen_item array element to empty, since $input_order_arr would not contain anything when you haven't submitted a form.
You should append to the session array only if there is a nonempty $input_order_arr array:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['item-title']) && !empty($_POST['item-price'])) {
$item_title = test_input($_POST['item-title']);
$item_price = test_input($_POST['item-price']);
array_push($input_order_arr,$item_title,$item_price);
$_SESSION['chosen_item'][] = $input_order_arr;
}
}

How to avoid PHP "Illegal string offset warning" when comparing an variable that will either be an array or null

I am a beginner learning PHP alongside a course on Lynda.com. In the website being built, the navigation menu is made by querying a database for "subjects" and "pages" and then making a table.
Each of these "subjects" and "pages" are links that send an ID number to $_GET to refresh the page and load the specific content. The problem is either the subject array or the page array will always be null (because only one type of thing can be clicked on at once). This is causing the webpage to always throw an "Illegal string offset warning".
if (isset($_GET['subj'])) {
$sel_subject = get_subject_by_id($_GET['subj']);
$sel_page = "NULL";
} elseif (isset($_GET['page'])) {
$sel_page = get_page_by_id($_GET['page']);
$sel_subject = "NULL";
} else {
$sel_subject = "NULL";
$sel_page = "NULL";
This is at the top of the .php, and shows at least one of these variables will be NULL instead of an array.
$subject_set = get_all_subjects();
while ($subject = mysqli_fetch_array($subject_set)) {
echo "<li";
if ($subject['id'] == $sel_subject['id']) {
echo " class =\"selected\"";
}
echo "><a href=\"content.php?subj=" . urlencode($subject['id']) .
"\">
{$subject["menu_name"]}</a></li>";
$page_set = get_pages_for_subject($subject['id']);
echo "<ul class=\"pages\">";
while ($page = mysqli_fetch_array($page_set)) {
echo "<li";
if ($page['id'] == $sel_page['id']) {
echo " class =\"selected\"";
}
echo "> {$page["menu"]} </li>";
}
echo "</ul>";
}
This is the part of the code that generates the navigation menu. One of the if statements will always try to get an array value from a variable that is null.
Am I doing something wrong? Is this just an inherently bad way of making a navigation menu for the site? I know the course I am using is old, so perhaps PHP programming has made this method obsolete.
I am a huge fan of empty(). I don't care of isset can tell you that it is set as an empty string or null. I want to know if there is data, whether it's a string or an array.
Try replacing your isset calls with ! empty()
if (! empty($_GET['subj'])) {
//
} elseif (! empty($_GET['page'])) {
//
} else {
//
}
Also, be sure that you are not taking input directly from the user. If you know those _GET vars are to be integers, clean them before using them.
$page_id = (integer) $_GET['page'];
if (! empty($page_id) {
// check it out, they can't send us junk anymore!
If they aren't integers, you will have to have a more discerning method of verifying them before using them. But that is a different question, eh?

How to get a single variable attached to the URI?

I don't seem to able to acquire a GET variable that is attached to the URI.
The codes are => at the controller
...
parse_str($_SERVER['QUERY_STRING'], $_GET);
....
$data['ti'] = $this->input->get('hamleno');
this->load->view('anasayfa', $data);
The codes are => at the view the link is
...
<div class="row"><?php for ($b=0; $b<=(count($hml)-1); $b++) { ?><?php echo $hml[$b]." "; ?> <?php } ?></div>
The link is working. I have added the
$config['uri_protocol'] = "PATH_INFO";
to the config.php file.
However I am not able to get the $ti variable
if ($ti){
$t=$ti;
}else{
$t = $this->input->post('t');
if (!$t) $t = 0;
if( $this->input->post('ileri') ) {
$t=$t+1;
if($t>($uz-1)){
$t=$uz-1;
}
} // Forward button was pressed;
if( $this->input->post('geri') ) {
$t=$t-1;
if($t<0){
$t=0;
}
} // Back button was pressed;
}
I'm not familiar with codeigniter, but I've always passed GET variables in this manner:
URL = www.site.com/folder/webpage.php?myvariable=myvalue
I would retrieve that value this way:
$x = $_GET['myvariable'];
or with codeigniter: (I think)
$x = $this->input->get('myvariable');
Tailored to your example, I would personally de-obfuscate your loop code just a little and instead of switching from PHP to HTML and back in one line, I would simply echo both from PHP like this:
(I also don't exactly understand the url you're using, so here is my approximate)
<?php
for ($b=0; $b<=(count($hml)-1); $b++)
{
echo '',$hml[$b],' ';
}
?>
I found out how Codeigniter solves the problem =>
$get = $this->uri->uri_to_assoc();
if(isset($get['hamleno'])){
$data['ti'] = $get['hamleno'];
}
This sends the $b assigned to $hamleno together with all the other stuff in $data.
Thank you all for your kind comments

Passing array of data to other page using session in PHP

I have some problem passing array of data in Php using session:
In my class, I have this function:
public function check_dupID($id)
{
$this->stmt="select id from student where id='$id'";
$this->res = mysql_query($this->stmt);
$this->num_rows = mysql_num_rows($this->res);
if($this->num_rows == 1)
{
while($this->row = mysql_fetch_array($this->res))
{
$dup_id = $this->row[0];
return $dup_id;
}
}
}
This code checks for duplicate ID of a student. Now, the reason for this is that I uploaded the file in the database using ".csv" file.
Before Uploading it I put all the data in the csv file into an array. Now, I check it one by one:
//created the variable for checking
$id = $check->check_dupID($array[0]);
if($id == TRUE)
{
session_start();
$_SESSION['id']; = $id;//passing it to the next back to array again.
$redirect->page($error);
}
Now when it redirect it gives me the result of an "Array" and if I parse it using foreach it shows only one id but there is more than of that. I want to know how to display it all.
This code will return the duplicate id when it is found for the first time. If you want to return all the duplicate ids, then add them into an array using the while loop and then return it.
To do this modify your code like this:
public function check_dupID($id)
{
$this->stmt="select id from student where id='$id'";
$this->res = mysql_query($this->stmt);
$this->num_rows = mysql_num_rows($this->res);
$dup_id = array();// added here to prevent invalid argument supplied to foreach loop error if nothing is found
if($this->num_rows >1)
{
while($this->row = mysql_fetch_array($this->res))
{
$dup_id[] = $this->row[0];// adding duplicates into the array
}
return $dup_id;
}
}
This code fixes my problem:
if($id == TRUE)
{
$get_id = array();
$get_id[] = $id;
session_start();
$_SESSION['id']; = $get_id;//passing it to the next back to array again.
$redirect->page($error);
}

Check if the fetched array is empty or not PHP?

I am trying to check if the mysql_fetch_array() function returns an empty array or not. But my code doesn't seem to work. Here I want to ensure that if the array is empty I want to display under construction message.
Code :
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
while($fetchSet = mysql_fetch_array($exeQuery)) {
if(count($fetchSet) == 0) {
echo "This Page is Under Construction";
}else{
// something else to display the content
}
}
How do I check to acheive such feature ?
use mysql_num_rows to count number of rows. try this.
$exeQuery = mysql_query($queryContents);
if(mysql_num_rows($exeQuery)== 0){
echo "This Page is Under Construction";
}
else{
while($fetchSet = mysql_fetch_array($exeQuery)) {
// something else to display the content
}
}
You really should be using mysql_num_rows http://us2.php.net/manual/en/function.mysql-num-rows.php
However, on a side note, you should use php empty() instead. http://us2.php.net/empty
When you use mysql_fetch_array(), it returns the rows from the data
set one by one as you use the while loop.
If there will be no record, while loop wont execute. In this case, declare a boolean variable and make it true if it enters the while loop. Like:
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
$recordExists = 0;
while($fetchSet = mysql_fetch_array($exeQuery)) {
if($recordExists == 0 )
$recordExists = 1;
// something else to display the content
}
if($recordExists == 0 ){
echo "This Page is Under Construction";
}
Hope this works!
You can do it this way:
while($r[]=mysql_fetch_array($sql));
// now $r has all the results
if(empty($r)){
// do something
}
source: php doc
Your code inside the while loop never runs if there are no results. mysql_fetch_array returns null/false if there are no more results. What you need yo do is check with mysql_num_rows first, before the while.
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
if(mysql_num_rows ($exeQuery) == 0) {
echo "This Page is Under Construction";
}
while($fetchSet = mysql_fetch_array($exeQuery)) {
// something else to display the content
}
Try this
if(empty($fetchSet)
{
echo "This Page is Under Construction";
}
else
{
// something else to display the content
}

Categories