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.
Related
I have been trying everything to achieve this task, but it is rather difficult.
I am trying to do this in Wordpress as shortcode.
The shortcode itself is fine, I don't need any help with that, but just the output here which is giving me a difficult time. The Shortcode has an attribute that can be used to show the ID of the list using $listID
As an example, I have 3 database tables.
complete (variables: id, itemID, listID, userID)
item (variables: id, listID, description, creator)
list (id, name)
What I need to do is show a list from a shortcode variable, in this case database id 1 for the list. Then show the items in that list (using listID in item variable as well as wordpress user function to grab the ID of the logged in user and compare it to the creator variable of the item) -- and have the completed marked in there (using itemID, listID and the logged in user to wordpress to compare with the userID).
I tried this for SQL, but it returned nothing
global $wpdb;
$q_checked = $wpdb->prefix.'checked';
$q_item = $wpdb->prefix.'items';
$q_list = $wpdb->prefix.'list';
$q_results = $wpdb->get_results("
SELECT * FROM (($q_item INNER JOIN $q_list ON $q_item.listID = $listID)
INNER JOIN $q_checked ON $q_list.id = $q_checked.listID;
I also tried this with sql but it only shows from the two tables and not the third, and it will show all instead of excluding the completed.
$q_items = $wpdb->prefix.'items';
$q_checked = $wpdb->prefix.'checked';
$q_result = $wpdb->get_results("SELECT $q_items.title, $q_checked.userID FROM $q_items INNER JOIN $q_checked ON $new_items.id = $q_checked.itemID");
I thought about using a foreach, but none of the above would work well with that would it? Since you can only use one result. Maybe if I could do 2 separate foreach, 1 for the items in the list but exclude them if the id of the item matches the itemID in the completed database? Then do another foreach that would show the completed items for that list.
<?php foreach($q_result as $i ) {
$userID = $i->userID;
$itemNAME = $i->title; ?>
<?php if($userID === ''.$current_user->ID.'') { ?> <?php echo $itemNAME; ?><?php }?>
<?php }; ?>
I honestly think I should rethink the entire thing. Maybe I am overcomplicating it?
This is a fairly standard MySQL query:
SELECT i.description, i.creator,
IF(c.id IS NOT NULL, 'Completed', 'Not Completed') AS status
FROM item i
LEFT JOIN complete c
ON c.itemID = i.id AND
c.listID = i.listID AND
c.userID = ?
WHERE i.listID = ?
The ? placeholders represent parameters that you would bind to the current user ID and list ID supplied by your shortcode.
This performs a left join from items to completed items, and checks for a match on all join conditions. If a match is found, then a row will exist in c, and we mark the item as completed. Otherwise, the c.id will be NULL and we mark it as not completed.
I have 3 tables:
chatmsgs with the columns
itemid, sender, receiver, message, datetime, status
users with the columns
userid, username, phone, email, avatar, online, password
items with the columns
itemid, category, make, type, mainimage, title, price
I am trying to create a list of chats between the current user and some other user on a specific item and order the list by the chat with the most recent message (based on timestamp).
My current query is this:
<?php
$currentuser=$_SESSION['userid'];
$sqls="SELECT DISTINCT itemid,sender,receiver FROM chatmsgs ORDER BY datetime DESC";
$results=mysqli_query($db,$sqls);
while($rows=mysqli_fetch_assoc($results)){
$itemid=$rows['itemid']; $sender=$rows['sender']; $receiver=$rows['receiver']; #$message=$rows['message'];
$sqll="SELECT * FROM items WHERE itemid = '".$itemid."'";
$resultt=mysqli_query($db,$sqll);
while($roww=mysqli_fetch_assoc($resultt)){
$itemid=$roww['itemid']; $title=$roww['title']; $status=$roww['status']; $userid=$roww['userid'];
#$sqlx = "SELECT * FROM users WHERE userid = '".$userid."' AND userid != '".$currentuser."'";
$sqlx = "SELECT * FROM users WHERE userid = '".$userid."'";
$resultx=mysqli_query($db,$sqlx);
while($rowx=mysqli_fetch_assoc($resultx)){
$avatar=$rowx['avatar']; $username=$rowx['username']; $user=$rowx['userid'];
$sq="SELECT * FROM chatmsgs WHERE itemid = '".$itemid."' AND ((sender = '".$sender."' AND receiver = '".$receiver."') OR (sender = '".$receiver."' AND receiver = '".$sender."')) ORDER BY id ASC";
$resul=mysqli_query($db,$sq);
while($ro=mysqli_fetch_assoc($resul)){
$message=$ro['message'];
$ldate=date_format(date_create($ro['datetime']),"M d");
}
echo '
<li>
My list item
</li>
';
}
}
}
?>
I have so far been able to list the chats but I'm unable to sort it.
I know this is not the best way to do this but it's the only way I know how. Would appreciate better ways.
I would start by getting all chat messages associated with just the given user in question. By doing a UNION as both the sender and receiver, if you have an index on each column respectively, the query should be very fast. From that, you can now query the rest of the data all in one quick run something like below.
You can order the data by whatever... From your while loops, it looked like you were doing all things for a given Item ID before moving to the next, so I have the order by clause by the item ID. Now, from within each item, I have ordered by the date/time in descending order with newest chat message first, but you could change that.
Another possible change is you may want the items displayed based on which is the MOST RECENT item that has chat activity first. For example, if a chat from someone was from a year ago, vs one that was just this week, you might want the current first. I would alter the query slightly.
select
um.itemid,
cm.message,
cm.datetime,
cm.status,
uFrom.username senderName,
uFrom.avatar senderAvatar,
uTo.userName receiptName,
uTo.avatar receiptAvatar,
i.category,
i.make,
i.type,
i.mainImage,
i.title,
i.price
from
( select distinct itemid
from chatMsgs
where sender = $currentuser
UNION
select distinct itemid
from chatMsgs
where receiver = $currentuser ) UM
JOIN ChatMsgs ch
on UM.ItemID = ch.ItemID
JOIN Users uFrom
on ch.sender = uFrom.userid
JOIN Users uTo
on ch.receiver = uTo.userid
JOIN Items i
on ch.itemID = i.itemid
order by
um.itemid,
cm.datetime desc
The format is not in php format, but you can see the only place you need a parameter is where the user ID is. All the details come along in the results including the respective avatars, titles, messages, from user and recipient user too. Take what you need in one query.
I would expect two individual indexes on your chatmsgs table. One on the sender, one on the receiver.
i have an array where i can get id's from a database table, now i need to extract those values as i run a domain link array such as: domain.com/page?id=1
Now this page will bring a category, lets say A category with ID 1 i need to list items under this category on the same database table example products, i can use it without a filter now i need a filter using arrays, here is my code, thank you in advance.
$query ="SELECT * FROM tablename WHERE id = '".$id."' DESC";
before this i have on my php code:
$id = $_GET["id"];
So when i call from this table all comes out, but i need to filter where category 1 (example) have items, not all items with category 2, 3, 4 etc.
With my code i can get the item id as the link with array works fine for example: domain.com/page.php?id=1, but here is the catch, i get item id 1 and i need let's say category id 2, if i run the same link with id=2 i get item id 2 and that's not what i want.
I need to retrieve those values as arrays, any idea? Thank you in advance!
EDITED
Table structure example:
Items
ID, Name, Category
I need Category from Items as a filter like this: domain.com/?id=2&category=2
So i get all items under row Category only
Update your URI to something like this domain.com/page.php?id=1&category=2
$category = $_GET["category"];
$query ="SELECT * FROM tablename WHERE id = '".$id."' AND `Category` = '".$category."'";
Pass the query string parameter optionally
domain.com/page.php?id=1&category=2
Add the where clause dynamically like this
$query ="";
$conact =" where 1=1 ";
if(isset($_GET['id']))
{
$conact.=" and id=".$_GET['id'];
}
if(isset($_GET['category']))
{
$conact.=" and category=".$_GET['category'];
}
$query ="SELECT * FROM tablename $conact DESC";
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 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