I have a PHP script that outputs a list of reviews in a table and orders them by the date they were submitted - (similar to have Trip Advisor ratings work).
Below I have included how the table heading are set out:
NAME || DATE || REVIEW || RATING
Below I have listed the code:
//run a query to find all the fields in the review table that belong to the specific hall, using the id in the url ($current_id)
if ($r = $db->prepare("SELECT * FROM reviews WHERE hall_id = :current_id ORDER BY overall DESC")) {
//bind the parameters used in the above query using the 'current_id' variable
$r->bindParam(':current_id', $current_id);
//Execute the prepared query
$r->execute();
//search review table for all fields and save them in $review
$reviewtemp = $r->fetchAll();
foreach( $reviewtemp as $review) { ...
ORDER BY date DESC orders the reviews by the date. However, when the user clicks on the 'RATING' header in the table, I need the reviews to be ordered by the highest rating (which is a number). So ORDER BY date DESC would change into ORDER BY rating DESC.
I'm unsure whether I have to create an entire new page (and simply change 1 word of my php script) to do this, or if there is a more simple and efficient method?
I wouldn't make whole new page, I would say have a variable that you can change that you would use in the order by in your query.
$orderby = 'rating';
And then your query would have "ORDER BY $orderby DESC"
EDIT
If you make the date header a link to "yourscript.php?orderby=date", you could have something like this on "yourscript.php"
switch($_GET['orderby']){
case 'date':
$orderby = 'date';
break;
default :
$orderby = 'rating';
break;
}
Up to you, but when I do this I use tablesorter. Take a look, it lets you display the results and clicking on the headers reorders on the fly, no new queries. It also lets you sort by more than one column by holding shift.
I whipped up a fiddle for you to check out.
http://tablesorter.com
Related
I have a query a Wordpress include which does the following:
$sql = "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'merchant_id' LIMIT 6";
$results = $wpdb->get_results($sql);
foreach ($results as $row)
{
echo $row->meta_value . ",";
//sprintf("SELECT * FROM retailers WHERE advertiserId = '%s'", $row->meta_value);
}
//clean all results
$wpdb->flush();
It parses all pages custom fields (merchant ID numbers), and returns any unique distinct values, separated by a comma. This bit works great.
ie: The above may return: 1301,345,723,134,1435
What I also have is a separate MySQL table of about 20 fields, three of which are the MerchantID, programmeName, and commissionMax. Each value from the CSV correlates with the MerchantID in the database.
Regardless of the amount of merchant ID's that appear in the CSV - I need to parse them all, but show the three highest commission rates (commissionMax), as well as the programmeName.
I managed to get connected to my external database and retrieve the appropriate values (using the commented code above) however this showed all of the retailers information.
Any advice?
Use the following query with limit:
SELECT * // select all fields
FROM table_name // from your table
WHERE MerchantID IN (your_ids_here) // IDs received from previous query or wherever
ORDER BY commissionMax DESC // descending sort by commissionMax field
LIMIT 3 // take first 3 results
I have a php script that displays records from a database. It's probably not the best script, as I'm very new to php.
I've added an additional column in my table and would like to keep a count in that column to show me how many times each of the records have been viewed.
Heres the part of the code I think i need to add the code to... if i need to post the entire page i will, but i just figured i could add the line to this part.
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
}
the new column name is 'views' and i just want to add 1 to it each time a record from the database is viewed.
any help greatly appreciated.
Add a new field views to the table.
When, user views the page, fire the SQL.
$query = "UPDATE offers SET views = views + 1";
mysqli_query($con,"update offers set views = views + 1");
If you have added the column, it probably has a NULL value. Either set the value to 0, by doing:
update offers
set views = 0;
Or use:
update offers
set views = coalesce(views, 0) + 1;
You can change your code with this rewritten code assuming that your Table has a column views (datatype int).
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
if($result){
$query2 = "UPDATE offers SET views=views+1;
mysqli_query($con,$query2);
}
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
Or if you need to track the view counts for individual records, you need to modify your code a bit. And probably you need to add one more field in the database for eg. id (datatype int) which can distinguish between different records.
Please clear your problem properly.
As far as i have analysed your code it brings out the following case.
There are different records for tradingConty, and whenever a user views that particular record(one of the tradingCounty record) by clicking that or any other action specified, the php script is set to increament the view count for that particular entry(we can get that by id) in the database.
If thats the scenario, we can easily generate a code accordingly.
I use the following code to get information from my MySql data base in order to display items :
$sql = "SELECT product,size1,size2,prdname,price
FROM multisize
WHERE online= 'online' AND category = 'backcovers' AND campaign = '".$brand."'
ORDER BY size1 DESC, size2 DESC ";
Some times I have the same item that needs to be displayed in two campaigns. (ex. iphone4, iphone5)
is there any way to tell my code that this item should be displayed in those two campaigns or should i just create duplicate items ?
You may use GROUP BY clause in your query.
I'm developing in php/sql a web application where users will be able to post items that they'd like to sell ( kinda like ebay ). I want non-members to be able to comment on the items or ask queries about items.
My problem is I want to display each item as well as any comment/query made about that item, in a similar manner as the way Facebook wall works.
I want to "append comments"(if any) to each item. The comments table is linked to the items table via column item_id. And the items table is linked to users table via column user_id. I have left joined users table with items table to display item details, i tried to left join comments table as well so that there are 3 joined tables.
That fails because no comments are displayed and only one item is displayed, despite there being multiple entries in each table. Here is the code i,m using.
$database->query
('
SELECT sale.*, query.*, users.id AS userid, users.username as user
FROM sale
LEFT JOIN users ON sale.user_id = users.id
LEFT JOIN query on sale.id = query.item_id
where category = "$category" ORDER BY sale.id DESC
');
$show = " "; //variable to hold items and comments
if ($database->count() == 0) {
// Show this message if there are no items
$show .= "<li class='noitems'>There are currently no items to display.</li>" ;
} else {
$show .= "<li>";
while ( $items = $database->statement->fetch(PDO::FETCH_ASSOC) )
{
$show .= "
//show item details in html
";
while( $query = $database->statement->fetch(PDO::FETCH_ASSOC) )
{
$show .= "
//show queries below item details
";
}
$show .= "</li>" ;
}
Welcome to Stackoverflow!
I recommend you taking a look at pdo. If you are already using mysql_ functions, then I recommend you switch. More on that can be found here.
Now that your pointed to the direction of to what functions to use when connecting/running queries, you now should create your tables. I use phpmyadmin for managing my database, I find it very good, but it's up to you what you use. Once you've decided on the service you use to manage your database, you should then learn how to use it by doing some google searches.
Now you need to set up your table and structure it correctly. If you say you're having items, then you should make a table called items. Next create the columns to the properties of the items. Also I recommend reading about Database Normalization, which is a key aspect of setting up your SQL tables Etc.
Once you have everything set up, you've connected to your database successfully Etc. You now need to set up the "Dynamic Page". What I mean by this is, there's only one page, say called 'dynamic', then a variable is passed to the url. These are called GET HTTP requests. Here's an example of what one would look like: http://example.com/item?id=345.
If you've noticed, you'll see the ? then the id variable defined to 345. You can GRAB this variable from the url by accessing the built in PHP array called $_GET[]. You can then type in your variable name you want to fetch into the []'s. Here's an example.
<?php
$data = $_GET['varname']; // get varname from the url
if(isnumeric($data)){ // is it totally made out of numbers?
$query = "SELECT fieldname FROM table WHERE id=:paramname";
$statement = $pdo->prepare($query); // prepare's the query
$statement->execute(array(
'paramname'=>$data // binds the parameter 'paramname' to the $data variable.
));
$result = $statement->fetch(PDO::FETCH_ASSOC); // grabs the result of the query
$result = $result['fieldname'];
echo 'varname was found in the database with the id equal to:'.$data.', and the result being: '.$result;
}
?>
So now you can see how you can grab the variable from the url and dynamically change the content with-in the page from that!
Hope this helped :)
I know things are escaped incorrectly, but I am trying to write a previous/next query to get the next id and previous id within an order, but my output does not match the phpmyadmin sorting, which it should. I just have the 'next' written, and would write the previous with reverse conditions. This query seems to give me the next highest ID value number within the order...I need the next or previous in the order index...can anyone help?
$db = JFactory::getDBO();
$query = "SELECT image_id FROM #__jxgallery_images WHERE image_id >".$currentid."' ORDER BY '".$ordering." ".$direction." LIMIT 1";
// Executes the current SQL query string.
$db->setQuery($query);
// returns the array of database objects
$list = $db->loadObjectList();
// create the list of ids
foreach ($list as $item) {
$next = $item->image_id;
echo $next.'<br/>';
}
echo 'The next ID in this sort state is '.$next.'<br />';
?>
This is phpmyadmin and it is right...
SELECT * FROM `jos_jxgallery_images`
ORDER BY `jos_jxgallery_images`.`hits` DESC
LIMIT 0 , 30
I have now matched this query in my code to get the same results. My variables fill in the ($ordering) 'hits' field and the 'desc' ($direction) within my clause. That works fine. The image_ids and hits aren't special...just numbers. When hits are ordered, the image_ids are resored to match. I don't need the next value of image_id as to what is in the field. I need the next row or previous row, regardless of value, based on the current image_id I plugin.
These are actual image_ids LIMIT 5, and these are Ordered by the hits field Descending:
52791
52801
52781
52771
52581`
Now if the current image I'm looking at has an id of 52791, then previous should be nothing and next should be 52801. What my query is doing I think is giving me an image_id of a higher valued number as 'next' because that is the next highest VALUED image_id, not the next row. I can see why in the query, I am asking for greater than...but I just need the next row
I think the problem is with your WHERE condition: WHERE image_id >".$currentid."'
If I understand what you're trying to do, one way to do it is this:
$query = "SELECT image_id FROM `#__jxgallery_images` ORDER BY ".$ordering." ".$direction." LIMIT 2";
$db->setQuery($query);
$list = $db->loadObjectList();
$next_item = $list[1]->image_id;
Notice that the WHERE condition is removed from the query, and I also changed LIMIT 1 to LIMIT 2. This way, the query basically returns your top value and the one with the next highest "hits" value.
I hope this helps.