PHP/MySQL select query issues - php

I was wondering if anyone could give me a hand. I currently have 3 tables as follows:
users(user_id, username, first_name, last_name, password)
module(module_id, name, crn)
userModule(user_id, module_id)
What would be the best way to access this? From doing basic research it looks like a RIGHT JOIN would be appropriate...
How would I go about looking at the modules table based on the user_id variable?
I gave it ago here but it doesn't seem to work.
$result = mysql_query("SELECT * FROM module JOIN userModule ON (module.module_id = userModule.module_id) JOIN users ON (userModule.user_id = users.user_id) WHERE user_id = 2");
$row = mysql_fetch_row($result);
echo $row[0];
echo $row[1];
echo $row[2];

$result = mysql_query("SELECT * FROM modules LEFT JOIN userModule ON userModule.module_id = modules.module_id WHERE userModule.user_id = 2");
It should work!
Better yet, if you only want to get modules info:
SELECT modules.* FROM modules ....
I used LEFT JOIN but there are several other methods : RIGHT JOIN, INNER JOIN or FULL JOIN. See what's the difference between those methods here: http://www.w3schools.com/sql/sql_join.asp
Also, you should always add " or die(mysql_error());" after your mysql_query(). If the query is wrong (bad formatting, miswritten fields, etc.) it will print a useful error.

Related

How to fetch data from a joined query in PHP

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.

Mysql query working from command line but only half working in PHP

I have two tables
1.owners
id
firstname
lastname
2.product
id
id2
id3
item
SELECT * FROM owners LEFT JOIN product ON product.id=owners.id where firstname='Jezebel';
Works fine from the command line returning all relevant items from owners and product but using the following PHP
$result = mysql_query("SELECT * FROM owners LEFT JOIN product ON product.id=owners.id where firstname='".$_POST['fname']."'")
only returns results from the table owners.
I have googled extensively and don't see anyone else with this problem.
$fname= $_POST['fname'];
$result = mysql_query("SELECT * FROM owners LEFT JOIN product ON product.id=owners.id where firstname='$fname'")
First, make your query similar to this
$query = sprintf("SELECT * FROM owners LEFT JOIN product ON product.id=owners.id where firstname='%s'",mysql_real_escape_string(trim($_POST['fname'])));
$result = mysql_query($query) or die(mysql_error());
var_dump(mysql_fetch_assoc($result));
and let me know the result so I can update this answer.
First of all: You have two table which match on autoincrement column id?
However, try this?
SELECT tb1.id, tb1. firstname, tb1.lastname, tb2.id, tb2.id2, tb2.id3, tb2.item FROM owners AS tb1 LEFT JOIN product AS tb2 ON tb2.id=tb1.id where tb1.firstname=$fname
I have found the error. It was nothing to do with the select statement. I had a typo in the display code. It should have been like this
echo "</td><td>";
echo $row['id3'];
But was like this instead
echo "</td></td>";
echo $row['id3'];
Thank you all for your help.

JOIN MySQL doesn't work

I've tried everything, but nothing works.. Even in an other code I wrote, it works. But for some reason it won't now.
I want to join two tables where the ID = userID. When I load the page, I get this error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL
result resource in
/home/ynxwleus/domains/mustseenmovies.nl/public_html/films/userinfo.php
on line 17
Is there anyone who can help me with this problem?
Code:
$userID = $_SESSION['s_userID'];
echo $userID;
$query = "SELECT userID, userName, userFrontname, userSurname, filmID
FROM users
JOIN seenIt
ON users.userID = seenIt.userID
WHERE (userID ='$userID')";
$res = mysql_query($query);
while ($row = mysql_fetch_array($res)) {
echo $row['userName'];
echo $row['userFrontname'];
echo $row['userSurname'];
echo $row['filmID'];
}
Thanks in advanced!
Your where clause needs an alias:
WHERE (users.userID ='$userID')
Your select clause also needs an alias on the userId:
SELECT users.serID, userName, userFrontname, userSurname, filmID
In fact, it is a really good idea to ALWAYS use aliases:
SELECT u.userID, u.userName, u.userFrontname, u.userSurname, si.filmID
FROM users u join
seenIt si
ON u.userID = si.userID
WHERE u.userID ='$userID'
The original query has syntax errors, because the SQL engine does not know which userID is being referred to. Oh, you are thinking "that's obvious because on clause specifies that the values are the same." Well, humans are smarter than SQL compilers, at least when it comes to common sense.
If your query returns an error, then mysql_query returns a boolean false. You can print out this error using mysql_error().
$res = mysql_query($query) or die(mysql_error());
Additionally, mysql_fetch_row will not work on a boolean, so you get the compilation error.
Your query has an error, as Gordon pointed out.
Additionally, I would suggest to not use mysql anymore, since it is deprecated. Use MySQLi, or PDO instead.
$query = "SELECT userID, userName, userFrontname, userSurname, filmID
FROM users
JOIN seenIt
WHERE users.userID = seenIt.userID
AND users.userID = ".$userID." ";

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.

Bad query - INNER JOIN

I am getting a bunch of undefinded index warnings when i print out my data from a SQL query, when i remove the INNER JOINS most of the warnings disappear. I am not sure what is causing that error.
My code is here:
<?php
$id = $_GET['id'];
$sql = "SELECT * FROM updates INNER JOIN clients ON updates.c_id = clients.c_id INNER JOIN pages ON updates.page = pages.p_id INNER JOIN projects ON updates.p_id = projects.p_id WHERE u_id='$id' LIMIT 1";
echo $sql;
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
// put update_id in hidden form and pass it to the next page
$u_id = $row['u_id'];
?>
<h4>Viewing update for <i><? echo $row['fname'] ." ". $row['lname'] ?></i> for their <i><? echo $row['p_title']; ?> project</i></h4>
<h4><b>Posted on: </b> <? echo $row['date_submitted'] = date("F j, Y, g:i a"); ?></h4>
Any idea on what I can do? The reason I have the INNER JOIN for CLIENTS is because "fname" and "lname" are stored there
clients.c_id = updates.c_id
Where I have: "p_url" "p_title" those are stored in the table PROJECTS which is also:
clients.c_id = projects.c_id
Edit with new problem
My code is here:
$sql = "SELECT
updates.u_id AS u_id,
updates.date_submitted AS date_submitted,
updates.deadline AS deadline,
updates.description AS description,
updates.priority AS priority,
pages.page_name AS page_name,
clients.fname AS fname,
clients.lname AS lname,
projects.p_url AS p_url,
projects.p_title AS p_title,
FROM updates INNER JOIN clients ON updates.c_id = clients.c_id INNER JOIN pages ON updates.page = pages.p_id INNER JOIN projects ON updates.p_id = projects.p_id WHERE u_id='$id' LIMIT 1";
The error is:
Not unique table/alias: 'clients'
Edited answer:
Ah, I incorrectly assumed it had to do with SQL indexes. It appears it's actually a PHP error, related to you trying to print out array elements that don't exist.
For all of your prints that include elements of $row ($row['deadline'], etc), you need to make sure that there are actually columns named that being returned by your query. If there's not a column named "deadline", that attempt to print it is going to generate the warning.
Edit again: since this got bumped up, I guess I'll go into a little more detail.
First of all, as bobince points out, you have SQL injection possible. The first line should be:
$id = intval($_GET['id']);
if $id will always be an integer, and mysql_real_escape_string() if it could be a string.
Second, SELECT * is generally bad form, especially in a case with joins. I don't know exactly which tables particular fields come from, but your query should look more like this, where you select only the fields you're actually going to use:
$sql = "SELECT clients.fname, clients.lname, projects.p_url, projects.p_title, updates.date_submitted ".
"FROM updates ".
"INNER JOIN clients ON updates.c_id = clients.c_id ".
"INNER JOIN pages ON updates.page = pages.p_id ".
"INNER JOIN projects ON updates.p_id = projects.p_id ".
"WHERE updates.u_id='$id' ".
"LIMIT 1";
Next, $u_id gets set to exactly the same value as $id already had, so it's kind of a pointless variable.
Finally, on the last line, you have:
<? echo $row['date_submitted'] = date("F j, Y, g:i a"); ?>
I'm not sure what you're expecting this to do, but it's going to assign date("F j, Y, g:i a"); to $row['date_submitted'] and then end up printing out "true" or "1" or something, that's probably not what you were going for.
Newest problem: You both try to select from clients, and join clients, you can't do both, at least without giving one of them an alias.
I don't think this has anything to do with the SQL (but I could be wrong). You might take a look at this thread for a start.
SELECT * FROM updates INNER JOIN clients
When you ‘SELECT *’ you get each column from both tables. Because columns can have the same names, the column names generated automatically by ‘*’ are prefixed with the table name. So your associative array will contain indexes like:
updates.u_id
clients.c_id
...
So when you try to access the array using an unprefixed column name such as 'page_name', it fails because that index isn't there.
You can use the full column name ('pages.page_name'), or you can explicitly give your own column names by saying:
SELECT updates.u_id AS u_id, pages.page_name AS page_name, ...
FROM updates JOIN client ...
u_id='$id'
Whoops, SQL injection hole. Congratulations, you are this week's 1000th winner of the obligatory xkcd link.
mysql_real_escape_string() is your friend. (Even better: mysqli parameterised queries.)
<? echo $row['deadline']; ?>
Whoops, HTML injection hole. htmlspecialchars() is your friend.

Categories