So this script works like this. It takes the tags you have chosen as your interests and compares it with the other users tags. This script below gives me the output of how many tags me and the other person have common.
$get_userinfo = mysql_query("SELECT * FROM users") or die(mysql_error());
while($userinfo = mysql_fetch_array($get_userinfo)) {
$usertags = $userinfo['tags'];
$tagsdata = explode(" ", $usertags);
$interestsdata = explode(" ", $interests);
$result = array_intersect($interestsdata, $tagsdata);
echo "Count under this belongs to ".$userinfo['name']."";
echo count($result);
echo "<br />";
}
Now, I want first, this script also displays me in the list so I see how many tags I have common with myself and I want to remove myself. And second, how do I list it so the person with highest number (most tags common) get displayed at the top and descending.
Add a condition to exclude yourself from your own query:
SELECT * FROM users WHERE user_id != [your user id]
To order by the number of tags, you need to issue an aggregate function in your SQL statement to group results by the tag and user. Without seeing your table structure I can only offer a very generalized statement
SELECT username, tag, count(tag) FROM users JOIN tags ON x = y WHERE user_id != [your user id] GROUP BY user_id, tag_id ORDER BY count(tag) DESC
Another option is to collect your data, and sort through it with PHP after you already know how many tags each user has in common. See http://php.net/manual/en/function.sort.php for information on sorting arrays.
You should also start using PDO or mysqli as the mysql functions have been officially deprecated.
I also strongly advise you to not put multiple tags in one database field.
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.
Whilst populating a table based on ids and labels from different tables, it appeared apparent there must potentially be a better way of achieving the same result with less code and a more direct approach using LEFT JOIN but i am puzzled after trying to work out if its actually capable of achieving the desired result.
Am i correct in thinking a LEFT JOIN is usable in this instance?
Referencing two tables against one another where one lists id's related to another table and that other table has the titles allocated for each reference?
I know full well that if theres independent information for each row LEFT JOIN is suitable, but where theres in this case only several ids to reference for many rows, i just am not clicking with how i could get it to work...
The current way i am achieving my desired result in PHP/MySQL
$itemid = $row['item_id'];
$secid = mysql_query(" SELECT * FROM item_groups WHERE item_id='$itemid' ");
while ($secidrow = mysql_fetch_assoc($secid)) {
//echo $secidrow["section_id"]; //testing
$id = $secidrow["section_id"];
$secnameget = mysql_query(" SELECT * FROM items_section_list WHERE item_sec_id='$id' ");
while ($secname = mysql_fetch_assoc($secnameget)) {
echo $secname["section_name"];
}
}
Example of the data
Item groups
:drink
:food
:shelf
Item List
itemId, groupId
Group List
groupId, groupTitle
The idea so outputting data to a table instead of outputting "Item & Id Number, in place of the ID Number the title actually appears.
I have achieved the desired result but i am always interested in seeking better ways to achieve the desired result.
If I've deciphered your code properly, you should be able to use the following query to get both values at the same time.
$itemid = $row['item_id'];
$secid = mysql_query("
SELECT *
FROM item_groups
LEFT JOIN items_section_list
ON items_section_list.item_sec_id = item_groups.section_id
WHERE item_id='$itemid'
");
while ($secidrow = mysql_fetch_assoc($secid)) {
//$id = $secidrow["section_id"];
echo $secidrow["section_name"];
}
I am using PHP with MySql. I need a query which should fetch me results according to my requirements.
I have a table property_features_table which has properties with some features.
In the front end I have a search functionality. When a user selects multiple features suppose
balcony,wifi,2-bedroom etc., He should be shown with properties having ALL the features he selected.
But when I use the following code, I am getting results (properties) which has atleast one of the features.
$featuresString = implode("','",$features);
$featuresString = "'".$featuresString."'";
$query = " SELECT * FROM property_features_tbl WHERE property_features_tbl.feature_id in (".$featuresString.")";
$features is an array which contains user selected features.
I want to display properties which has all the features selected by the user. Help me in writing the query.
Assuming you just want the property ids, then something like this:-
<?php
$featuresString = implode("','",$features);
$featuresString = "'".$featuresString."'";
$feature_count = count($features);
$query = " SELECT property_id, COUNT(*) AS feature_count
FROM property_features_tbl
WHERE property_features_tbl.feature_id in (".$featuresString.")
GROUP BY property_id
HAVING feature_count = $feature_count";
?>
I think I don't understand how 'sort' works, so please don't judge me. I really searched all day long.
I have a movies table with actors column. A column it's named "actors". The actors are links separated by space " ". The order of the links it's very important.
I explode the links into an array which looks like [0]-> link0, [1]->link1, ...
I have the actors table where every actor also has it's movies links. I don't want to make 20 different sql searches so I made a variable with all the links I want, like this ( WHERE actor_link = link1 OR actor_link = link2 OR .. )
The problem is this. The search will probably find first the link7, and so my sorting it's gone. What can I do to keep that order from the movies table. I want to display the actors by popularity in the movie, not the order of my database.
Can you give me another method to search the actors without making 'x' sql searches and still keeping the order?
$actors[] = explode(" ", $row['actors_link']);
$x=0;
$actors2 = '';
while ($actors[0][$x]) {
$actors2 = $actors2 . "`link_imdb_actor` = " . "'".$actors[0][$x]."' OR ";
$x++;
}
$actors2 = substr($actors2, 0, -3);
$sql = "SELECT * FROM `actors` WHERE $actors2";
$sql_result = mysql_query($sql) or die(" ");
while ($row3 = mysql_fetch_array($sql_result)) {
echo $row3['link_imdb_actor'];
}
So, the movie Hotel Transylvania has Adam Sandler, Andy Samberg and Selena Gomez. My search shows Selena Gomez, Andy Samberg, Adam Sandler because this is the order from my database. How can I sort the sql results by the order of the actors array? Thank you!
To expand on Arjan's comment, if you want to be able to actually use the actor data (e.g. search with it) I would recommend at least two more tables. One called actors with the fields actorID, firstName, and lastName. The other table would be castings with the fields castingID, actorID, movieID, and castingOrder.
Each castingID will then link an actor to a movie - this would make for easy searches of every movie a particular actor has been in or every actor in a particular movie.
The castingOrder field can be used to maintain the order you want.
I need your existing code to really get the gist of what's going on.
I will make one suggestion in your query. Instead of saying WHERE actor_link = a OR actor_link = b OR actor_link = c do this instead:
WHERE actor_link IN (link1, link2, link3)
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 :)