I have a PHP results page which starts off "first-pass" with ALL rows returned. It's a search listing of all pizza places in the county.
SELECT * from pizzeria;
Then the user can drill down into more detail... the page also has a CSS dropdown menu where the user can pick a specific neighborhood (which carries a URL):
href="samepage.php?neighborhood=HELLSKITCHEN"
which then changes the query after I pick up the $_GET[]
SELECT * from pizzaria WHERE nbh=(the $_GET[] variable sent in the URL);
but I'd like the page to call itself and I have header("Cache-Control:no-cache"); at the top.
I'm trying to create a first-pass or first visit flag variable with the isnull() function:
if (is_null($firstpass)) {
$query = SELECT all the records from the pizzaria table
} else {
$query = SELECT only the records WHERE I $_GET[] the value from the reloaded URL
}
It seems though that the $firstpass variable doesn't stick on reloads. Should I SESSION that variable? (though still have the problem of constantly resetting it)
Or maybe implement some other approach?
I know I can redirect to a separate second page and javascript back to this page to avoid "headers already sent", but I want to avoid the round-trip back to the client.
Is there a known best practice on reloads with new info? Kinda new to PHP here. thanks
Maybe I didn't understand well your problem but why wouldn't you do :
if (!isset($_GET['example'])) {
$query = 'SELECT * FROM pizzerias';
} else {
$query = 'SELECT * FROM pizzerias WHERE pizzeria = \'.mysql_real_escape_string($_GET['example']).\' LIMIT 1';
}
at the first pass because, it seem that the $_GET variable is set only when the user choose a pizzeria?
Here is a more targeted answer.
NOTICE: mysql_* functions are being depreciated, so use PDO instead. In my example I'm being semi-lazy and not using PDO.
//Connect to database and define table up here
...
if(!isset($_GET['neighborhood')){
$q = "SELECT * FROM pizzeria;";
}else{
$q = sprintf("SELECT * FROM pizzeria WHERE nbh=%s",mysql_real_escape_string($_GET['neighborhood']));
}
$query = mysql_query($q);
foreach($row = mysql_fetch_array($query,MYSQL_ASSOC){
//display the updated view of restaurants.
}
I would also suggest that you use jQuery for that Web 2.0 effect. It's really nice when you select from a drop-down menu and things magically move without a page reload.
Related
I've got rendered page with lots of items and i want to have item-specific page accessed by clicking the link
while($row = mysqli_fetch_array($result))
{
echo "<h3>".$row['Brand']." ".$row['Model']."</h3>";
//more details
}
So by clicking $row['Brand']-$row['Model'] I'd like to be redirected to the page with this item. Can i do that somehow? As the only way i know - is to insert new .php file and pass some unique item's id from SQL via URL or post request by that is not SEO-friendly way, so I'd like to avoid that.
You'll need to use the rewrite in apache(assuming that's your webserver) This is a nice tutorial. Or look into using a framework that handles that for you. Something simple like CodeIgniter or Laravel.
You have to do it from the mysql_query function using where clause pointing to the column you to be filter the results.
echo "<h3>".$row['Brand']." ".$row['Model']."</h3>";
$brand = (isset($_GET['brand'))?mysql_real_escape_string($_GET['brand']):'';
$model = (isset($_GET['model'))?mysql_real_escape_string($_GET['model']):'';
$query = "SELECT * FROM cars WHERE brand='$brand' AND model='$model'";
$result = mysql_query($query);
I am doing this animation tool where I fetch a value from my database and then a picture will animate to a certain position. My question is if it is possible to retrieve data constantly or like every 5 seconds?
Somehow like this:
while(autoretreive){
$data = mysql_query("select * from ......");
}
UPDATED from here
Thanks for your answers! Made it a little bit clearer what to do! Maybe I can explain better what I'm doing in my code.
I am doing this animation program as said, where balls with information is moving around to different locations. I have one value that will be updated frequently in the database, lets call it 'city'.
First at previous page I post the balls of information I want based on the 'city' and I do like this (simplified):
$pid = $_POST['id'];
$pcity[0] = $_POST['city'];
$pcity[1] = $_POST['city'];
$pcity[2] = $_POST['city'];
//...
$while(autoretrieve) { // HOW TO?
$data = mysql_query(select * from table where city == $pcity[0] OR $pcity == [1] //...);
while($rows = mysql_fetch_array($data)){
$city = $rows['city'];
$id = $rows['id'];
if($city == example1){
"animate to certain pos"; //attached to image
}
else if($city == example2){
"animate to certain pos"; //attached to image
}
}
}
So for every update in the database the image will animate to a new position. So a time interval of 5 seconds would be great. I'm not an expert in coding so sorry for deprecated code. Not so familiar with AJAX either so what is going to be imported to the code? It is also important that the page is not reloading. Just the fetch from database.
you can do it with ajax and javascript
make one javascript function which contains ajax code to retrive data from database
and at your page load using setTimeout call your ajax function at every 5 second
You can use sleep function to control how often you want to fetch data.
while(autoretreive){
$data = mysql_query("select * from ......");
//output your data here, check more in link about server sent events bellow
sleep(5);
}
Since you haven't specified how you plan to access data I'm writing this answer assuming Server-Sent Events as they are only ones that make sense according to your question.
Now all this was according to your question which wasn't very clear on how do you plan to use data. Again you'll most likely want to fetch data using ajax, but Server Sent Events can also be a good way you could achieve this.
And don't use mysql_* it's deprecated, switch to PDO or mysqli_*
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.
I have, let's say 5 email threads (a, b, c, d, e), each email is different. Each email contains a link to a landing page.
Then I have a php landing page wire frame that pulls data from a SQL database (currently mysql, but may change so using PDO) to populate different content depending on which email thread the viewer comes from. So 1 php landing page, but 5 rows in the database to populate 5 different versions of that landing page depending on which email viewer links from.
My current query in my landing page looks like this:
<?php
$result = "SELECT body_copy FROM low_engagement WHERE thread_segment = 'a3'";
$stmt = $connection->prepare($result);
$stmt->execute();
$body_copy = "";
while($row = $stmt->fetch()) {
$bodyCopy = $row['body_copy'];
}
?>
If I manually change the WHERE clause entitled thread_segment across the values of 'a1', 'a2', 'a3', 'a4', and 'a5' my landing page updates with the appropriate content in accordance with each of the 5 threads.
My question, is it possible to perhaps mark the href in the HTML email so when that link links to the landing page it could some how interact with the landing page telling it which of the 5 email/email links it is coming from and dynamically alter the thread_segment value appropriately?
I am fairly new to PHP/PDO so I am open to suggestions and/or direction. My current research on the matter has me still researching possibly passing a variable via one of several means, but most of the content I find is in regards to forms.
Any insight is greatly appreciated!
Yep, just pass the thread_segment in the href of the email, like:
some.url.com/page.php?s=a3
and change your pdo to something like:
<?php
$result = "SELECT body_copy FROM low_engagement WHERE thread_segment = :s";
$stmt = $connection->prepare($result);
$stmt->bind_param(':s', $_GET['s']);
$stmt->execute();
$body_copy = "";
while($row = $stmt->fetch()) {
$bodyCopy = $row['body_copy'];
}
?>
You can use HTTP GET Variables to pass information using a URL.
e.g. the Link: http://yourlink.org?segment=a1
The ?segment=a1 associates segment with the value a1, you can add more parameters by seperating with & like so: ?segment=a1&language=en
I am being very explicit with the variable names here, generally you would try to keep the url as short as possible.
You can then access this variable in PHP using $_GET:
$_GET["segment"]
Check out the PHP Docs for further information
http://www.php.net/manual/en/reserved.variables.get.php
let say I have a post that can be found on page post.php?pid=60 but if the user changes the url to post.php?pid=95 the page is displayed all weird is
there a way I can have them redirected to another page that says post dosn't exist or something? If so how would I do this? And is this the best way to handle none existent pages? If not what is preferred?
I'm using PHP & MySQL if that helps.
get the post from DB by the given $_GET["pid"]
if a post is found (ie. given pid existed)
then display it normally
else include the error page content / use header to redirect to the error page, etc.
Hope the logic helps you
well, you could try to select the post from the database, and if the query brings nothing you redirect to the page that shows all posts. it makes more sense to me than exhibiting a "page not found" message (in this case). the idea is something like this:
$result = query('SELECT * FROM posts WHERE id=60');
if( ! $result)
redir('all_posts.php');
this is just for picturing the problem. i'm assuming that the query function returns false, null or even an empty array if no rows are returned, instead of the usual mysql resource.
just remember to add an exit; (could be in the redirect function) to not let the page renders all weird.
You should be checking if there is data being returned in the database, if there is not then you display the error message.
Do you have any supporting code? Here is a mock-up:
$pid = isset($_GET['pid'])?(int)$_GET['pid']:0; // use the ternary operator to set a default value
if (!empty($pid) {
$res = mysql_query("SELECT columns FROM table_name WHERE pid = $pid") or trigger_error('MySQL Returned: ' . mysql_error());
$rows = mysql_num_rows($res);
if ($rows > 0) {
// display the data
}else {
// There is no data so display the no-data page
}
}
It may not work exactly for you, as you will have to tweak it, but should give you a rough idea.