How to look up values from a different table? - php

Currently, I have a log file of messages in one table in a MySQL database. Among some other stuff, it contains the sender id, and the message itself. I want to make a way to display the log on a website.
I have a separate table that contains the sender ids and the name of the person (which is what I actually want to display).
Are there any better ways than simply running another query? While that would work, that's pretty expensive as it requires a new query for every entry. Ideally, I'd like something that would map the id --> name in an array, but I can only find things that will put everything from one row into an array (aka, horizontally), but I need entries "vertically".
I'm using PHP by the way...
Thanks!
Kevin

Learn about JOIN statements. This is exactly what you need.

I believe you are looking for something like this:
SELECT `name`, `message` FROM `msgtable` INNER JOIN `sendertable` USING(`sender_id`)

Related

Search tags in mysql table with PHP

I have a table with some submissions, this table has a tags field, and I need to search in it.
The data is saved in JSON format in the table, like this: ["basic","example","html","chart"]
I'm trying to find a way to search all rows in the tags fields, but not sure how it can be done the best way when it is in this format.
The user submits an tag to search, like: html, then I need to search all rows for that tag, without to much overhead.
I know most people use to say: what have you tried yourself?
- well, nothing. As I have no clue how to do this, I know how to search in sql and all that. but never tried it in this logic.
There is no "best way" to search in this format. There is no way at all.
No wonder you have no clue how to do that. I'll tell you more - no one knows it either. Tags should never be stored in json format. It is like as if you built a car, placing wheels on the roof. And then come asking, how to drive it.
You have to learn database basics first. And then create your tables proper way. making a separate table for tags. Storing each on a separate row. After that you will be able to search a tag usual way, using JOIN query to attach the corresponding records to the result.
$sql = "SELECT a.* FROM articles a, tags t WHERE aid=a.id AND tag=?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($tag));
$data = $stmt->fetchAll();
You should create another table tag with fields name, post_id.
I believe that is the best solution to do a search feature.
If you do not have permission to create database table. It depends on how many posts you have. a few? hundreds or even more? If there is not a huge rows of your post table. You can fetch all of them and decode to PHP Array and then use string comparison.
Or maybe, you can give up the database way, just handling with a cache file. We're only need to write cache if user create/modify a post.
But you also can use the unreliable way, using like operator in mysql.
You should take a look at the MySQL fulltext index.
Take a look in the manual and this Zend Developer article
But you shouldn't use fulltext searching for many columns.
In one of my projects I worked around it by concatenating to be searched columns in a TEXT column and apply to the fulltext index on it.
It's simple you can try using like query
SELECT * FROM `post` WHERE `tags` LIKE '%html%';
In PHP Variable:
$tag = "html";
$query = mysql_query("SELECT * FROM `post` WHERE `tags` LIKE '%'.$tag.'%'");

Combining different table queries in db with PHP and displaying all results on one page

I have been trying to create a database for fun to get a better understanding of databases and using PHP to query them for a website I'm messing around with. Pretty much I have one database with 4 tables when a user enters a search term in a PHP search box my code searches the database for any entries containing the search term. Now I can easily get my code to search individual tables, but I cannot seem to get it to search all 4 tables and display the results on the same page.
info: making a database for skyrim
Table names: classes, powers, skills, shouts
column names: name, information
Here is a snippet of the code I have that works so far:
$raw_results = mysql_query("
SELECT *
FROM `xaviorin_skyrim`.`shouts` , `xaviorin_skyrim`.`classes`
WHERE (CONVERT(`UID` USING utf8) LIKE '%".$query."%' OR
CONVERT(`Name` USING utf8) LIKE '%".$query."%' OR
CONVERT(`Information` USING utf8) LIKE '%".$query."%')
") or die(mysql_error());`
Literally all I thought I would need to do is change the table name from "shouts" to say "classes" in a new raw_results line of code but that didn't work. I have attempted unions and joins and either keep screwing them up or just don't understand how to properly format them.
echo "<p><h3>".$results['Name']."</h3>".$results['Information']."</p>";
The code above this text is what displays the results on the page on my website... it works but I don't know how to combine the information from all 4 tables into one page. If I'm going about this in the wrong way and anyone can point me in the right direction I would GREATLY appreciate it... I've been trying to research the problem without finding a proper answer for near a month now.
The problem with your approach is that relational databases do a cross join when there are several query results from two different tables. So basically every match in one table will be combined with every match from the second table. When you have 3 entries in the first and 4 in the second table, you will get 3 * 4 = 12 entries in your query result. If you add more tables, you get even more results. You want to do a full text search in several tables that are totally unrelated, thus creating some kind of non-existing relation via cross joining them will not be useful.
What you actually want to do is a UNION ALL (UNION is slower because it prunes duplicates) of several queries:
SELECT name, information, 'shouts' AS tablename FROM shouts WHERE ...
UNION ALL
SELECT name, information, 'classes' AS tablename FROM classes WHERE ...
This will do search queries on every single table and then place the results in a single result. Also note that I added a third column to each query to ensure that the originating table is not lost after merging the results.
Unless you need to do some sorting afterwards, I would suggest that you do all statements separately. Combining them this way will most likely make the post-processing more complex. And several single queries will also be faster than one big query with UNION statements.
And as I mentioned in the comments: Don't use mysql_* functions!

PostgreSQL Query and PHP Assistance

Directly under this small intro here you'll see the layout of the database tables that I'm working with and then you'll see the details of my question. Please provide as much guidance as possible. I am still learning PHP and SQL and I really do appreciate your help as I get the hang of this.
Table One ('bue') --
chp_cd
rgn_no
bgu_cd
work_state
Table Two ('chapterassociation') --
chp_cd
rgn_no
bgu_cd
work_state
Database Type: PostgreSQL
I'm trying to do the following with these two tables, and I think it's a JOIN that I have to do but I'm not all that familiar with it and I'm trying to learn. I've created a query thus far to select a set of data from these tables so that the query isn't run on the entire database. Now with the data selected, I'm trying to do the following...
First and foremost, 'work_state' of table one ('bue') should be checked against 'work_state' of table two ('chapterassociation'). Once a match is found, 'bgu_cd' of table one ('bue') should be matched against 'bgu_cd' of table two ('chapterassociation'). When both matches are found, it will always point to a unique row within the second table ('chapterassociation'). Using that unique row within the second table ('chapterassociation'), the values of 'rgn_no' and 'chp_cd' should be UPDATED within the first table ('bue') to match the values within the second table ('chapterassociation').
I know this is probably asking a lot, but if someone could help me to construct a query to do this, it'd be wonderful! I really do want to learn, as I don't wish to be ignorant to this forever. Though I'm not sure if I completely understand how the JOIN and comparison here would work.
If I'm correct, I'll have to put this into seperate queries which will then be in PHP. So for example, it'll probably be a few IF ELSE statements that end with the final result of the final query, which updates the values from table two to table one.
A JOIN will do both level of matching for you...
bue
INNER JOIN
chapterassociation
ON bue.work_state = chapterassociation.work_state
AND bue.bgu_cd = chapterassociation.bgu_cd
The actual algorithm is determined by PostreSQL. It could be a merge, use hashes, etc, and depends on indexes and other statistics about the data. But you don't need to worry about that directly, SQL abstracts that away for you.
Then you just need a mechanism to write the data from one table to the other...
UPDATE
bue
SET
rgn_no = chapterassociation.rgn_no,
chp_cd = chapterassociation.chp_cd
FROM
chapterassociation
WHERE bue.work_state = chapterassociation.work_state
AND bue.bgu_cd = chapterassociation.bgu_cd

PHP MYSQL Query Array Field

Ok. I'm using MySQL and PHP. I have a table called "Pictures" and a field in that table called "Tagged." This field is an array of UserIds which I imploded and stored as a string.
example: 114,159,14,334
Lets say I want to return all the rows in "Pictures" where a particular UserID, say 14, exists somewhere in the "Tagged" field's array. How can this be done?
select * from pictures where FIND_IN_SET(14,Tagged);
Start it with a , and end with a , like this: ,114,159,14,334, and then do a SELECT FROM Pictures WHERE tagged='%,14,%'
Just an idea, I really don't know... I've never done this before. Traditional blog tagging may be similar enough that you could look up some tutorials to learn from them.

Need help querying across two databases (first time trying to do this)

I have two databases I need to work with, db_site and db_forum (these are generic names, FYI).
db_site has a table called main-news, which has a forumurl field which holds a forum thread id and a views field which holds the current pageviews for the article entry in the database. db_forum has a table called forum_threads which has a tid field and a replies field.
I have two things I need to do, one using just the replies and another using the replies and the views. I assume once the former is figured out the latter won't be much more than adding some extra parts, so I'm concerned with the former for the time being.
Not sure how I should approach this since the two tables are in different databases. The login I'm using has access to both of them (AFAIK), so that isn't the problem, it's more of the syntax involved. Would what I'm looking to do be something like this, perhaps?
SELECT
db_forum.forum_threads.replies AS replies
FROM
`db_forum.forum_threads` AS f,
`db_site.main-news` AS s
WHERE
f.tid = s.forumurl
That's a rough guess, from what I can find online abut doing this type of query. Any help is appreciated. :)
First of all, you should indent your SQL code properly. That long line was almost unreadable.
SELECT
db_forum.forum_threads.replies AS replies
FROM
`db_forum.forum_threads` AS f,
`db_site.main-news` AS s
WHERE
f.tid = s.forumurl
Then, make use of your table aliases "f" and "s". You introduced them, so you have to use them:
SELECT
f.replies AS replies
FROM
`db_forum.forum_threads` AS f,
`db_site.main-news` AS s
WHERE
f.tid = s.forumurl
Finally, you should remove the unnecessary quoting:
SELECT
f.replies AS replies
FROM
db_forum.forum_threads AS f,
db_site.main-news AS s
WHERE
f.tid = s.forumurl
If the names of the fields are indicative of their function, then f.tid refers to an identity column while s.forumurl does not. Normally the s.formurl in this case would be a foreign key. Just a guess.

Categories