Mysql Query with two tables php - php

I was wondering how to do a query with two tables in php?
I have this single query
?php
$sQuery = "Select * From tb_columnas Where col_Status='activo' Order by col_ID DESC";
$result = mysql_query($sQuery, $cnxMySQL) or die(mysql_error());
$rows_result = mysql_fetch_assoc($result);
$total_rows_result = mysql_num_rows($result);
if ($total_rows_result > 0){
do {
$id_columnas = $rows_result ['col_ID'];
$col_Titulo = $rows_result ['col_Titulo'];
$col_Resumen = $rows_result ['col_Resumen'];
$col_Fecha = $rows_result ['col_Fecha'];
$col_Autor = $rows_result ['col_Autor'];
?>
But I'd like to compare the col_Autor with au_Nombre which is in another table (tb_autores) and get au_Photo and other values from it, how can I do that?

You can do a simple join query without using the JOIN keyword by specifying the two tables in the FROM clause and establishing a relationship in the where clause.
For example
SELECT columns
FROM table1, table2
WHERE table1.field = table2.field

You are asking about SQL Joins, the practicing of putting two or more tables together in an SQL statement to return data from more than 1 table. You join the tables on a common column, such as author.authorid = book.authorid. I suggest looking up JOINS on google, there are many good articles.
A great article on it: http://www.sitepoint.com/understanding-sql-joins-mysql-database/

It sounds like you are looking for a join. Try something like the following:
SELECT * FROM tb_columnas JOIN tb_autores ON tb_columnas = col_Autor WHERE col_Status='activo' ORDER BY col_ID DESC

You need to understand joins for this.
Here you will find very good explanation of the same:
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

Related

mysql multiple WHERE from different tables

I want to output a nice user table. But my query needs a WHERE from multiple tables.
At the moment... my query looks like:
$statsTable = "someTable";
$userTable = "someOtherTable";
$someData = "SELECT stats.* FROM $statsTable stats, $userTable user
WHERE user.some_status = '0'
AND (stats.some_value BETWEEN $rangeFrom AND $rangeTo)
ORDER BY stats.some_value ASC
LIMIT 0,10";
then mysqli_query and so on...
The output(array) has 2 times the data from $statsTable and the WHEREs are not working. I just want to select the $statsTable...
How to proceed?
Thanks :)
$statsTable = "someTable";
$userTable = "someOtherTable";
$someQueryForData = "SELECT stats.*
FROM $statsTable stats
JOIN $userTable user
ON (user.id_stats = stats.id)
AND (user.some_status = '0')
WHERE (stats.some_value BETWEEN $rangeFrom AND $rangeTo)
ORDER BY stats.some_value ASC LIMIT 0,10";
Edit: explaining you're basically need a join, building query's the way you are doing makes them not as readable and you can't really associate your tables.
Using joins after you made your "ON" statement you may just add an "AND"
And use that conjunction as a where which is way faster the using the where ITSELF
Just use a join.
Join the tables on a unique ID and then you will have the values from both tables.
W3 Schools Joins
Should look like this
SELECT stats.* as stats, user.* as user
FROM statsTable
INNER JOIN userTable
ON stats.userId=user.userId
WHERE user.some_status = 0 AND (stats.some_value BETWEEN $rangeFrom AND $rangeTo)
LIMIT 0,10;

Mysql - SELECT columns from 2 tables using INNER JOIN error

This should be a basic question, but I haven't used Mysql for a very long time and forgot all the basic stuff. So SO programmers please bear with me.
I have 2 tables like this:
Table 1 (events): here
Table 2 (users): here
I would like to select all rows in the events table where event_invitees contains a username. I was able to do this using:
SELECT * FROM meetmeup_events WHERE event_invitees LIKE '%$username%'
Now I'd like to also select the event_invitees's photo from the users table (column called user_userphoto). My attempt to this was this:
$result = mysql_query("SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
WHERE event_invitees LIKE '%$username%'
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
This gave me an error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource
How can I do this? What am I missing? Can you give me some examples?
Thanks in advance! I'll be sure to accept the working answer!
You should change your mysql functions to either mysqli / PDO, although the problem seems to be the query itsef. Should be:
SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter
WHERE event_invitees LIKE '%$username%'
(the WHERE clause at the end)
Sql fiddle demo: http://sqlfiddle.com/#!2/852a2/1
Its just a matter of getting the query coded in the correct order, and you might like to make it a little more managable by using alias's for the table names
Try this :-
SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'
This of course assumes that all the column names are correct and the mu.user_username = me.event_inviter does in fact make sence because those fields are in fact equal
Additional Suggestion
You are not actually issuing the query for execution by mysql.
You have to do this :-
$sql = "SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'";
$result = mysql_query($sql);
$rows = array('mysql_count' => mysql_num_rows($result) );
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
Now in your browser using the javascript debugger look at the data that is returned. There should at least be a mysql_count field in it even if there is no 'meetmeup_user' array, and if it is zero you know it found nothing using your criteria.

Declare $row for two tables

I want to echo data from two tables to one variable. Here is the code that I have so far:
$sqlCommand = "SELECT * FROM News ORDER BY id DESC LIMIT 10";
$sqlCommand3 = "SELECT * FROM Users ORDER BY id";
$query = mysql_query($sqlCommand) or die(mysql_error());
$query3 = mysql_query($sqlCommand3) or die(mysql_error());
$count = mysql_num_rows($query);
if($count > 1) {
$News .= "";
// How do I add the query3 here?? along side the already existing one
while($row = mysql_fetch_array($query)) {
// some of the $row here are from query one and some are from query 3
$News .= "<div class=\"news-post\"> <img src=\"".$row['author']."\"><p>".$row['author']."</p> <h2>".$row['title']."</h2></div>";
} // close while
This isn't the right way to go about it, instead try using a SQL join. In this case, you'll want a unique FULL OUTER JOIN.
SELECT * FROM News
FULL OUTER JOIN USERS
ON News.id = Users.id
WHERE News.id IS NULL
OR Users.id IS NULL;
This should give you all rows containing all columns from both tables. Depending on the actual relationship, you may want some different kind of join (refer to previous link)..but this seems like what you were trying to accomplish in your example.
Warning: you are using the mysql_* extension which has been deprecated in PHP 5.5. Please use either mysqli_* or PDO.
Your User table should be linked to the News table by a oneToMany association.
So a user writes a news and a new is written by a user.
And you need to add a join in your SQL query.
$sql = 'SELECT u.username, n.* FROM News n JOIN User u ON n.user_id = u.id';
Then, you while only have to execute one SQL statement and display the result in you HTML.
Have look to this website.

php sql multiple queries into one

Part of my page I have lots of small little queries, probably about 6 altogether, grabbing data from different tables. As an example:
$sql_result = mysql_query("SELECT * FROM votes WHERE voted_on='$p_id' AND vote=1", $db);
$votes_up = mysql_num_rows($sql_result);
$sql_result = mysql_query("SELECT * FROM votes WHERE voted_on='$p_id' AND vote=0", $db);
$votes_down = mysql_num_rows($sql_result);
$sql_result = mysql_query("SELECT * FROM kids WHERE (mother_id='$p_id' OR father_id='$p_id')", $db);
$kids = mysql_num_rows($sql_result);
Would it be better if these were all grabbed in one query to save trips to the database? One query is better than 6 isn't it?
Would it be some kind of JOIN or UNION?
Its not about number of queries but amount of useful datas you transfer. If you are running database on localhost, is better to let sql engine to solve queries instead computing results in additional programs. The same if you are thinking about who should be more bussy. Apache or mysql :)
Of course you can use some conditions:
SELECT catName,
SUM(IF(titles.langID=1, 1, 0)) AS english,
SUM(IF(titles.langID=2, 1, 0)) AS deutsch,
SUM(IF(titles.langID=3, 1, 0)) AS svensk,
SUM(IF(titles.langID=4, 1, 0)) AS norsk,
COUNT(*)
FROM titles, categories, languages
WHERE titles.catID = categories.catID
AND titles.langID = languages.
example used from MYSQL Bible :)
If you really want to lower the number of queries, you can put the first two together like this:
$sql_result = mysql_query("SELECT * FROM votes WHERE voted_on='$p_id'", $db);
while ($row = mysql_fetch_array($sql_result))
{
extract($row);
if ($vote=='0') ++$votes_up; else ++$votes_down;
}
The idea of joining tables is that these tables are expected to have something in between (a relation, for example).
Same is for the UNION SELECTS, which are prefered to be avoided.
If you want your solution to be clean and scalable in future, I suggest you to use mysqli, instead of mysql module of PHP.
Refer to: mysqli::multi_query. There is OOP variant, where you create mysqli object and call the function as method.
Then, your query should look like:
// I use ; as the default separator of queries, but it might be different in your case.
// The above could be set with sql statement: DELIMITER ;
$query = "
SELECT * FROM votes WHERE voted_on='$p_id' AND vote=1;
SELECT * FROM votes WHERE voted_on='$p_id' AND vote=0;
SELECT * FROM kids WHERE (mother_id='$p_id' OR father_id='$p_id');
";
$results = mysqli_multi_query($db, $query); // Returns an array of results
Fewer queries are (generally, not always) better, but it's also about keeping your code clear enough that others can understand the query. For example, in the code you provided, keep the first two together, and leave the last one separate.
$sql_result = mysql_query("SELECT vote, COUNT(*) AS vote_count
FROM votes
WHERE voted_on='$p_id'
GROUP BY vote", $db);
The above will return to you two rows, each containing the vote value (0 or 1) and the vote count for the value.

SQL Query Optimization help

my foundation on SQL is pretty weak so I hope you could bear with me. I have three tables: contents, categories, and categorization. The setup was chosen since some content will belong to one or more categories.
I want to fetch contents and its corresponding categories.
This is an overly-simplified version of the current script, without error-checking routines:
$q = "SELECT * FROM contents WHERE contents.foo = 'bar'"
$resource = mysql_query($q);
$categoryFilter = array();
$q2 = "SELECT * FROM categorization WHERE ";
while($content = mysql_fetch_assoc($resource))
{
$categoryFilter[] = "content_id='" . $content["id"] . "'";
}
if(count($categoryFilter))
{
$q2 .= implode(" OR ", $categoryFilter);
mysql_query($q2);
}
That's the gist of it. I hope you get what I am trying to do. I don't know if I can actually use JOINS the content_id may be present in multiple rows in categorization. So what I did was to simply append multiple OR's, trying to fetch items one by one. I really would not like to use multiple queries in this scenario. I hope anyone could suggest an approach
Thanks for your time
One query should be enough to fetch data from all three tables:
SELECT categories.category_id #, other fields
FROM contents
INNER JOIN categorization ON contents.content_id = categorization.content_id
INNER JOIN categories ON categorization.category_id = categories.category_id
WHERE contents.content_id = 1 # AND other filters
Tweak the columns in the SELECT clause and/or conditions in WHERE clause according to your needs.
This should do the same thing as in your example:
$q = "
SELECT *
FROM
contents c
categorization ctg ON ctg.content_id = c.id
WHERE c.foo = 'bar'
";
$result = mysql_query($q);
If I understand it correctly, you can do this in one sql statement
SELECT *
FROM contents t1
JOIN categorization t2
WHERE t1.content_id = t2.content_id AND t1.foo = 'bar'
Also ensure that content_id is indexed both in 'content' and 'categorization'. You may find it worthwhile indexing 'foo' aswell, but it depends on how you are actually searching.

Categories