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.
Related
i have a small problem. I use two mysql queries for getting data.
First i want to get IDs from groups
$sqlGoups = "SELECT * from `groups` WHERE `Date`='$TodayDate' ";
$result = $conn->query($sqlGoups);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$IDgroups = $row["ID"];
With that, I'll get those IDs, for example 5, 7, 12, 15, 22
I want to put them all in the next mysql query:
$sqlNext = "SELECT * FROM `orders` WHERE ID = '$IDgroups' ORDER BY `ID` ASC ";
$result = $conn->query($sqlNext);
When I do this, I get the result only for the first ID (5). And I want for each
I can not INNER JOIN tables because I use this in next query.
I tried with foreach loop, but no effect.
Try this code
SELECT * FROM `orders`
WHERE ID REGEXP CONCAT('(^|,)(', REPLACE('$IDgroups', ',', '|'), ')(,|$)')
ORDER BY `ID` ASC
Just like #Elanochecer commented the best bet should be a JOIN statement, but if you wish to go through your route, you could use the IN and provide the IDs as comma separated string, your query should look similar to the one below:
...
$sqlNext = "SELECT * FROM orders WHERE ID IN ('$IDgroups') ORDER BY ID ASC ";
...
Also, confirm if $IDgroups is in the format 1,2,3,4
If you provide the schema I could come up with a workable JOIN statement for you, preferably you can create a repo with the schema
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;
I have a mysql query:
$query5 = mysql_query("SELECT * FROM `pages` WHERE (`id`='$switch' AND `rand`='$randID' AND `email`!='".$_SESSION['user']."') ");
And second:
$query5 = mysql_query("SELECT * FROM `pages_admin` WHERE (`pId`='$switch' AND `rand`='$randID' AND `admin`!='".$_SESSION['user']."') ");
I use a while loop to present data.
while($row = mysql_fetch_array($query5)) {}
I need one mysql query instead two.
If these tables are related you can JOIN them using the foreign key.
If I'm not mistaken this pId in the table pages_admin is a foreign key to the id on the table pages, is that correct?
If so, you could do something like this to you query:
"SELECT * FROM pages p
LEFT JOIN admin_pages ap on p.id = ap.pId
WHERE (`pId`=$switch AND `rand`=$randID AND `admin`!='{$_SESSION['user']}')"
Note that I've changed the syntax, instead of merging string you can use only one containing all variables you need.
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
I've two tables, users and coach_to_trainee. User can have multiple coaches, and the data is stored in coach_to_trainee columns coach_id and trainee_id.
I'm using coach_to_trainee table to print out data for the user, so he/she can simply see who is his/her coach.
<?php
$user = $_SESSION['login']['id'];
$q = "SELECT * FROM coach_to_trainee WHERE trainee_id='$user'";
$coachid = $db->prepare($q);
$coachid->execute();
while($row = $coach->fetchObject()){
$coachid = $row->coach_id;
echo '<li>'.INSERT_COACH_NAME.'</li>';
}
?>
However, this will only return the ID of the coach, and I need to return the name also, from table users.
How I'm supposed to do another query inside while() and use $coachid to find the correct user?
You have to use JOIN mysql clause, like this one:
SELECT u.name, u.id
FROM users u
LEFT JOIN coach_to_trainee ctt
ON u.id = ctt.coach_id
WHERE ctt.trainee_id = {$user}
You should be done with this one ;-)
Then in Your PHP use the selected values:
while($row = $coach->fetchObject()){
echo '<li>'.$row->name.'</li>';
}