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;
Related
I've a joined query in PHP, which I wanted to join 2 databases VIA the user ID, but I want to be able to fetch data from both tables (users & user_stats), although it's not letting me output any data from the user_stats table, which is leaving me to believe there's a error in my query..
Hence this being my first time using joined tables, could someone please guide me in the correct direction, so far I have:
$getMembers3 = dbquery("SELECT users.id, users.look, users.username
FROM users
JOIN user_stats
ON users.id = user_stats.id
WHERE users.rank < 2 ORDER BY user_stats.Respect DESC LIMIT 10");
Which I am trying to fetch Respects from user_stats VIA:
while ($member2 = mysql_fetch_assoc($getMembers3))
{
echo $member2['user_stats.Respect'] . '<br>';
echo $member2['username'] . '<br>';
}
Although it allows me to view their username from the users table, it won't allow me to view the user_stats.Respect. If someone could enlighten me in the right direction that'd be fantastic.
I always get confused when selecting from mutliple tables and this is how I generally resolve my confusion:
$getMembers3 = dbquery("SELECT users.id as id, users.look as look, users.username as username, user_stats.Respect as respect
FROM users
JOIN user_stats
ON users.id = user_stats.id
WHERE users.rank < 2 ORDER BY user_stats.Respect DESC LIMIT 10");
This way you know what the column names are expected to be. Sidenote, the result set will not have dots in the array keys.
Then you can access results from:
while ($member2 = mysql_fetch_assoc($getMembers3))
{
echo $member2['respect'] . '<br>';
echo $member2['username'] . '<br>';
}
Change your query adding the field in your select statement:
$getMembers3 = dbquery("SELECT users.id, users.look, users.username,user_stats.Respect
FROM users
JOIN user_stats
ON users.id = user_stats.id
WHERE users.rank < 2 ORDER BY user_stats.Respect DESC LIMIT 10");
As a side note you are using a deprecated api to access database that have been removed in PHP 7. Consider switching to PDO and prepared statements.
how would i go about ordering by a value that is not in the table where i am selecting from, in this instance the value $count1 is not in the table search.
count has the same identifying id as that of the thing it is being reffered to in the other table, this is where count1 is grabbed
$q = $db->prepare("SELECT COUNT(rating) FROM ratings WHERE id='$id' AND rating = 'd'");
$q->execute();
$count1 = $q->fetchColumn();
$query = "SELECT * FROM search WHERE title LIKE '$each' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();
that is from ratings, how would i go about ordering the entries like that, so that they are based off the number of count1 and are decided, i might have to implement something like
$query = "SELECT * FROM search WHERE title LIKE '$each' AND id = '$id' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();
Possible Duplicate: Mysql order by specific ID values
Same thing here, you'll just output your $count1as a comma separated string and add it in the SQL query as ORDER BY FIELD(COUNT,___comma_sep_string___)
ratings is a table, not a database. You can join tables or use subqueries to get the desired result, without having to make multiple queries.
You haven't described how the FOREIGN_KEY is set up in the ratings table, but assuming you have something ratings.search_id, this should work:
SELECT search.*, (SELECT COUNT(rating)
FROM ratings
WHERE ratings.search_id = search.id
AND rating = 'd'
) AS rating_count
FROM search
WHERE title LIKE '$each'
ORDER BY rating_count
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.
Ok so im working on my first ever php/mysql project having come from a software position. I am learning codeigniter and i have worked out that this mysql join will get me friends statuses based on an user.id, how do i add in all my posts to that do i have to do an AND query?
select * from friendships
join users on users.`id` = friendships.`friend_id`
join statuses on statuses.`user_id` = users.id
where friendships.`user_id` = 2
ORDER BY statuses.`id` desc
Any help greatly appreciated
Join query in codeigniter can be written as:
$this->db->select("*");
$this->db->from("friendships");
$this->db->join("users","users.id = friendships.friend_id");
$this->db->join("statuses","statuses.user_id = users.id");
$this->db->where("friendships.user_id",2);
$this->db->order_by("statuses.id","desc");
$result=$this->db->get();
or
$this->db->select("*");
$this->db->join("users","users.id = friendships.friend_id");
$this->db->join("statuses","statuses.user_id = users.id");
$this->db->where("friendships.user_id",2);
$this->db->order_by("statuses.id","desc");
$result=$this->db->get("friendships");
Well, CodeIgniter abstracts DB interaction through ActiveRecord (so writing full SQL query strings really isn't necessary). They do a better job of explaining it than I could:
http://ellislab.com/codeigniter/user-guide/database/active_record.html
Why not just add each user as a follower of themselves in your friendships table? So on registration you add them to users table and to the friendships table.
User 1 follows User 1 etc
You can also use this query in codeigniter
$query = $this->db->query("select * from friendships
join users on users.`id` = friendships.`friend_id`
join statuses on statuses.`user_id` = users.id
where friendships.`user_id` = 2
ORDER BY statuses.`id` desc");
$result = $query->row_array();
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