I got a Index page on which search page is included, and when I submit it, it passes values to find.php through action and method post. The code is below
if($_POST['searchsubmit']=="Search"){
$cat=$_POST['searchcategory'];
$area=$_POST['searcharea'];
$term=$_POST['searchbox'];
}
The above code is written on find.php, Now when I try to implement paging through basic paging method with where conditions to make appropiate search query
$where="where approved='yes'";
if($term!=""){
$where.=" and name like '%$term%'";
}
if($cat!=""){
$where.=" and category like '%$cat%'";
}
if($area!=""){
$where.=" and area like '%$area%'";
}
$start=0;
$end=5;
if($_GET['page']!="")
{
$start=$_GET['page']*$end;
}
Where $start is my initial limit, and $end is my number of records. For the first page of paging, I pass a variable page with 0 for first page
First
and my search query now becomes
$que="select * from shops ".$where." ORDER BY likes DESC limit $start,$end";
As soon as I click on "first", My new link become "/find.php?page=0"
and the post values which I recivied from index page search bar are lost.
Is there any way to retain those values ?The two methods which I though are sending them again through url with GET, or the other way is to store them in session.
Is there any third method available ?
Marc is absolutely right. Do not use the code as it is.
As an alternate solution to your problem -
Your page index.php (search form) submits to itself
Assemble your search query as querystring in index.php if its a post
Redirect to find.php with the assembled querystring
Every search information will always be in the querystring.
Use your pagination happily.
The comments are correct.
Use:
// Start the session
session_start();
// Save variables into session
$_SESSION['somevalue'] = $_POST['value'];
Then when any page calls session_start it will have access to $_SESSION['somevalue']
Also, you are wide open for SQL injection. Sanitize your values to ensure no one can put arbitrary sql code into the string. if you are using mysqli it should as simple as this:
// After connecting to the DB
$_POST['somevalue' = $mysqli->real_escape_string($_POST['somevalue']);
Then be sure to hardcode quotes around string values like you are doing.
If you want to be safer you can use prepared statement instead.
Hope this helps.
Related
I was wondering how to do the following best with PHP/MySQL and jQuery:
There is a basic search mask where you enter a city and a from-to-date. You process to the search-result page, where you then can narrow your search results with certain parameters (checkboxes, jQuery slider, text-input, ...). The search-results should then update on the fly without the whole page being reloaded...
I manage to use jQuery ajax and load to send information to another php file, perform e.g. a SELECT and return the results to the search detail page, but I don't know how to combine different changes that narrow the search results.
Furthermore, there are already results on the detail page, so I do not need to add more results but "delete" the results that do not fit anymore...
The thing is that each parameter to narrow the search is connected to another table in the database. Do I have to and how do I add joins to the original query...? Or am I thinking in the wrong direction?
Yes, this is absolutely the right direction. Use
$(document).ready(function() {
$('#ID_OF_YOUR_ELEMENT_TO_LOAD_INTO').load("load.php?parameter1=<?php echo $parameter1; ?>¶meter2=<?php echo $parameter2; ?>");
});
to get the results when the user gets on the page for the first time, to get the results according to your city and your dates.
Check in the load.php which parameters are set and use the ones that are set to build your query. Then, when the form (or forms, depending) are updated, you have to use .load again, like this:
$('#ID_OF_YOUR_FORM_BEING_UPDATED').change(function() {
$('#ID_OF_YOUR_ELEMENT_TO_LOAD_INTO').load("load.php?parameter1=<?php echo $parameter1; ?>¶meter2=<?php echo $parameter2; ?>¶meter3=<?php echo $parameter3; ?>");
});
Get the initial tuples via PHP/MySQL, save them into some Javascript structure and create the html needed to display the data with javascript from this structure.
Any time you want to filter the data you rewrite the html and check the filter condition on the fly, e.g. don't write tuples from the structure that don't match your filter condition.
You can see who this is done at http://www.wowhead.com
This is of course just one way. ;-)
You could always write some code to generate an SQL query based on passed arguments.
You ajax could query the page with a bunch of arguments in addition to your basic city and from-to date based on what the user has selected. If your page preserves the previous search options selected, it should be able to just let the user add on more options and keep processing them in the same way. Your php would then test to see if the arguments are set in the $_POST or $_GET variable ($_POST is more secure for ajax generally, but my example will use $_GET for simplicity) and build the query like that.
Example:
Javascript generates a query like searchAjaxHandler.php?city=Chicago&from=2012-03-01&to=2012-03-05&someColumnLowerRange=500&someColumnUpperRange=700
Your php script then processes as follows:
$query = "SELECT * FROM Data WHERE City=? AND Date > ? AND Date < ?";
$arguments = array($_GET['city'], $_GET['from'], $_GET['to']);
if (isset($_GET['someColumnLowerRange'])) {
$query .= " AND someColumn > ?";
$arguments[] = $_GET['someColumnLowerRange'];
}
if (isset($_GET['someColumnUpperRange'])) {
$query .= " AND someColumn < ?";
$arguments[] = $_GET['someColumnUpperRange'];
}
//execute the query
//using PDOs (google them...they are a good way to prevent sql injection and
//support multiple database types without modifying code too much), create a
//statement with the above query in put the statement in $statement
$statement->execute($arguments); //this uses the $arguments array to fill in the prepared statement's ?'s
//then do the stuff to get the retrieved rows out of the result returned
After all that, the javascript side would just to the same thing you were doing before by replacing all the previous results with the results that you got back.
I'm doing a website. There's a pagination, you click on links and they take you to the page you need, the links pass $_GET variable ( a href="?pn=2" ) and that works fine.
However when i add the category links (also contain $_GET variable
(a href="?sort=english") on the same page, which kind of sort the content on the page, and click it, the system simply overrides the url and deletes all the previous $_GET's.
For example, I'm on page 2 (http://website.com/index.php?pn=2)
and then I click this sorting link and what I'm expecting to get is this (http://website.com/index.php?pn=2&sort=english), but what I get is this:
(http://website.com/index.php?sort=english). It simply overrides the previous $_GET, instead of adding to it!
A relative URI consisting of just a query string will replace the entire existing query string. There is no way to write a URL that will add to an existing query. You have to write the complete query string that you want.
You can maintain the existing string by adding it explicitly:
href="?foo=<?php echo htmlspecialchars($_GET['foo']); ?>&bar=123"
Try using this:
$_SERVER['REQUEST_URI'];
On this link you can see examples. And on this link I have uploaded test document where you can try it yourself, it just prints out this line from above.
EDIT: Although this can help you get the current parameters in URL, I think it's not solution for you. Like Quentin said, you will have to write full link manually and maintain each parameter.
You could create a function that will iterate through your $_GET array and create a query string. Then all you would have to do is change your $_GET array and generate this query string.
Pseudocode (slash I don't really know PHP but here's a good example you should be able to follow):
function create_query_string($array) {
$kvps = array();
for ($key in $array) {
array_push($kvps, "$key=$array[$key]");
}
return "?" . implode("&", $kvps);
}
Usage:
$_GET["sort"] = "english";
$query_string = create_query_string($_GET);
You need to maintain the query parameters when you create the new links. The links on the page should be something like this:
Sort by English
The HTTP protocol is stateless -- it doesn't remember the past. You have to remind it of what the previous HTTP parameters were via PHP or other methods (cookies, etc). In your case, you need to remind it what the current page number is, as in the example above.
I have 2 php pages: query.php and result.php.
In query.php, I am executing a query (select) statement. It's returning a resultset
$rs = mysql_query($query);
Now I want to return this resultset from query.php to another page result.php and work with it. Like this:
In query.php:
return $rs
and in result.php:
$result = executeQuery($query) // we get the resultset in this variable
while ($row == mysql_fetch_array($result){
//do something
}
If the above is not recommended, please provide me with alternatives. But I want the query function and resultset in different pages.
You could just include results.php in your query.php page if you're just looking to keep the code separate in the source files but aren't actually required to redirect from one page to another:
In query.php:
$rs = mysql_query($query);
include "results.php";
In results.php:
while ($row == mysql_fetch_array($rs){
//do something
}
As far as trying to "return $rs" from one page to another that's not how PHP works. The return statement is only valid within a function. If you want to actually pass data from one PHP page to another and will be redirecting to that other page then you'll need to use either a session, a cookie, pass it in the URL (i.e. use GET) or use curl and add it as a POST var.
If this is really the way it must be, store the result set in a database somewhere or in a file and give each result a unique name. Then pass that name to the next page so it can be retrieved.
query.php will redirect to result.php?result_set=ab24sdfsdfklls for instance.
This has the added advantage that you can use the result_set as often as you want. Visitors can have multiple result sets during one visit. They can share the URL of the result set page with other people, etc.
Just be sure to eventually prune the data store as it will just keep on growing, but that's another matter entirely.
I need something simple; I have page where a user clicks an author to see the books associated with that author. On my page displaying the list of books for the author, I want a simple HTML title saying: 'The books for: AUTHORNAME'
I can get the page to display author ID but not the name. When the user clicks the link in the previous page of the author, it looks likes this:
<?php echo $row['authorname']?>
And then on the 'viewauthorbooks.php?author_id=23' I have declared this at the start:
$author_id = $_GET['author_id'];
$authorname = $_GET['authorname'];
And finally, 'The books for: AUTHORNAME, where it says AUTHORNAME, I have this:
echo $authorname
(With PHP tags, buts its not letting me put them in!) And this doesnt show anything, however if I change it to author_id, it displays the correct author ID that has been clicked, but its not exactly user friendly!! Can anyone help me out!
You could pull the author_id from the query string as you did using $_GET but beware you will need to validate what is coming through by the query. I hope you can see that without validation how bad of a security hole this is.
I am at work at the moment, but this is a quick example that should give you what you need without sanitizing your query.
$id = intval($_GET['author_id']);
// of course, perform more validation checks
// just don't assume its safe.
$sql = "SELECT authorname FROM authors_tb WHERE author_id=" . $id;
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo "The books for: " . $row['authorname'];
}
The reason why your approach wasn't working was because you utilize the $_GET URL parameter passing for author_name where you weren't supplying the parameters in the URL, just the author_id.
You don't send it in the query string, thus you can't get it from the $_GET array.
Just request it from the database using id.
An important note: Always use htmlspacialchars() when you display the data, coming from the client side.
This is because you do not define the author name in your get.
You should make the following your url:
<?php echo $row['authorname']?>
Or rather select the data from the database again, on the new page, using the ID you retrieved from the URI.
Author name won't be in $_GET. As your code stands, you only use it as the link title. It is no where in the address. Try this instead:
<?php echo $row['authorname']?>
It would be better to re-request it from the database using the author_id though.
EDIT:
To explain the problem in more detail. You have two pages, the new.php page and the viewauthorbooks.php page. You're sending users from the new page to the view page using the link you posted, right?
The problem with that is, your link assigns one variable in get. Here's the query string it would generate:
viewauthorbooks.php?author_id=13
What that will do is send the user to viewauthorbooks and place the value '13' in the $_GET variable: $_GET['author_id']. That is why the author_id is there and displays on viewauthorbooks. However, authorname is never passed to viewauthorbooks, it isn't in $_GET['authorname'] because you never set $_GET['authorname']. If you want it to be in $_GET, then you need your query string to look like this:
viewauthorbooks.php?author_id=13&authorname=bob
You can accomplish that using the new HTML code for the link I posted above. Look at it closely, there's a key difference from the one you have now.
However, it is generally discouraged to pass data through GET, because the query string is displayed to the user and it leaves you open to injection attacks. A better way to do this would be to use the author_id you are already passing to viewauthorbooks.php to retrieve the authorname from the database again. You can use the same code you used on the new.php page.
I have a tabled view in a while loop, where a user can view information on books.
For example, book ISBN, book name, read status...
Basically, when the user sets their 'readstatus' to 'complete' I want that specific table row to become grey! The logic is very straight forward, however I can't get my IF statement to recognise this:
if ($readstatus == 'complete') {
echo '<tr class="completed">';
}
else if ($readstatus != 'complete') {
echo '<tr class="reading">';
}
I'm obviously doing something wrong here, table content to change if the value of 'readstatus' = 'complete', if not, then output is the default
Why are you using $_GET? Does this information come from an HTML form or a URL etc... ?
I suspect you meant to change $readstatus = $_GET['readstatus']; to $readstatus = $row['readstatus'];.
$_GET is an aray of GET parameters which come from the query string.
$row is a row in your database, so if the information is in the database - which I suspect it is - you want to use $row instead of $_GET.
Try changing $readstatus = $_GET['readstatus']; to $readstatus = $row['readstatus'];
The $_GET function relies on the value being contained in the query string of the URL, and it has nothing to do with the database. I have a hunch you're trying to get the value from the database here and you're using the wrong function to do it.
$_GET['readstatus'] says the value is coming from the browser.
$row['readstatus'] says the value is coming from the database.
You need to decide which should take precedence-- probably the $_GET['readstatus']` because it's what the user wants to change. If that's the case, you need to update your database with the new readstatus before you requery the db for the dataset.