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.
Related
I have multiple tables and I want to access the fields in a specific table. Here are the table schemas:
Each tbl_acct has one tbl_unit. A tbl_unit has many tbl_groups and a tbl_groupcontact consist of the contacts and the related group. Every time I log in, I set a session where $_SESSION['unitid'] = $row['unitid'];.
What I wanted to do is to access the fields in the tbl_contacts. For now my code is here:
$data = $conn->prepare("SELECT * FROM tbl_groups LEFT JOIN tbl_groupcontact ON tbl_groups.id=tbl_groupcontact.group_id WHERE tbl_groups.unitid = ?");
$data->execute(array($_SESSION['unitid']));
foreach ($data as $row) {
echo $row['fname'] . " " . $row['lname']. "<br />";
}
As you can see, I can related the tbl_groups and tbl_groupcontact in my code however, I can't get the fields in the tbl_contacts. Am I missing something here? Any help would be much appreciated.
You need to join another table.
SELECT tbl_contacts.*
FROM tbl_groups
INNER JOIN tbl_groupcontact ON tbl_groupcontact.group_id = tbl_groups.id
INNER JOIN tbl_contacts ON tbl_contacts.id = tbl_groupcontact.contact_id
WHERE tbl_groups.unitid = ?
No need for (slower) LEFT JOIN btw - use it when you want to retrieve records from (left-side) table even when there's no match found in joined (right-side) table (it's columns will be filled with nulls in this case).
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 two tables, one is a user log which stores the user by number
timestamp / user_id / transaction_id / amount
the other is a user table which has the users number and their full name
user_id / fullname
I want to select the entire user log and display it, but instead of displaying their number, display their full name from the other table, but I can't get it working. I keep modifying the sql and breaking it. Is there a way to accomplish this with php postgresql or should I use a function?
I keep getting an error that user_id is integer and the fullname is not
Please assist.
$query = "SELECT * FROM user_log
INNER JOIN user_staff
ON user_log.user_id=user_staff.user_name
ORDER BY user_log_id DESC LIMIT 200;";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $myrow['timestamp'], htmlspecialchars($myrow['user_id']), htmlspecialchars($myrow['transaction_id']), htmlspecialchars($myrow['amount']));
}
?>
Use this query:
SELECT "timestamp", fullname, transaction_id, amount
FROM user_log
JOIN users USING (user_id)
Note that "timestamp" is a SQL reserved word and you should not use it for a column name. If you must use it, put it in double quotes.
Perhaps something like:
SELECT user_log.timestamp, users.fullname, user_log.transaction_id, user_log.amount
FROM user_log
INNER JOIN users
ON users.user_id=user_log.user_id
ORDER BY user_log_id
DESC LIMIT 200;
You can read up on SQL Joins here: http://www.w3schools.com/sql/sql_join.asp
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.
I have a query that grabs a bunch of diffrent tables using LEFT JOIN, and I was wondering if I could incorporate another table, but only count the values in it.
The problem
When I try to use COUNT(row_id) in the query with everything else, it only returns the count and nothing anything else.
$query = "
SELECT COUNT(subscriptions.sub_id) AS total_subscriptions,
postings.posting_id,
postings.posting_headline,
postings.posting_body,
postings.timestamp,
users.user_name
FROM postings
LEFT JOIN users ON postings.user_id = users.user_id
LEFT JOIN subscriptions ON postings.group_id = subscriptions.group_id
WHERE postings.group_id='" . $group['group_id'] . "'
ORDER BY postings.posting_id DESC
";
How can I fix this?
Add an explicit GROUP BY clause to the query.