JOIN MySQL doesn't work - php

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." ";

Related

Query works in phpmyadmin but same query won't return in PHP script

This is NOT a duplicate. None of the already existing threads have the same problem as me.
I have a database that stores athlete performances. It contains sessions, each session has sets, each set has "tables" (such as 4x100m, 12x50m and so on), and each table has times. I also have a table for athletes. Each athlete has an ID, each time links with the athlete through the AthleteID. Every session, set, timetable and time also have each unique IDs, used to link them with each other.
I want to make it so that when passing a session ID, it will return all the athletes that have at least 1 time in that session. I made a page that gets requests and the session ID is passed as GET search data (will make it POST later on). The request system works fine, but the problem is in the query. To do it I used inner joins to connect each table. This is my query (it is not the fastest method, but that's for another thread):
$q = "SET #evID = " . $method['sessID'] . ";";
$q .= "SELECT `athletes`.* FROM `events`
INNER JOIN `sets` ON `sets`.`EventID` = `events`.`EventID`
INNER JOIN `timetables` ON `timetables`.`SetID` = `sets`.`SetID`
INNER JOIN `times` ON `times`.`TableID` = `timetables`.`TableID`
INNER JOIN `athletes` ON `athletes`.`ID` = `times`.`AthleteID`
WHERE `events`.`EventID` = #evID
AND `times`.`TimeID` IN(
SELECT MIN(`TimeID`)
FROM `times`
WHERE `TableID` IN(
SELECT `TableID`
FROM `timetables`
WHERE `SetID` IN(
SELECT `SetID`
FROM `sets`
WHERE `EventID` = #evID
)
)
GROUP BY `AthleteID`
)";
Every single time I ran that in phpmyadmin it returned all the athletes, and the data was correct. However, when I run it in my script, the query value is false (such as if there is an error). I tried debugging like this:
$r = $db -> query($q);
var_dump($q);
var_dump($r);
var_dump($db->error);
The query is returned just fine (only difference is lack of newline characters), and when I copy what's returned in phpmyadmin the data is just the same. The rest however:
bool(false)
string(228) "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT `athletes`.* FROM `events` INNER JOIN `sets` ON `sets`.`EventID` = `...' at line 1"
Other users with the same problem have not really gone that far to find out if they're wrong, but I have. This post is not a duplicate, and I didn't find any solutions online. Could this be a problem with the amount of queries in a single string? (There is one for setting #evID and one for the actual selection). Please explain the solution and methods kindly as I'm only 13 and still learning...
As #NigelRen has suggested, please use parameterized prepared statement.
Assuming that
$sessionid is storing the value for EventID, and assuming that this variable is of integer type; and
$conn is the connection
Then for Mysqli, you can use:
//$q = "SET #evID = " . $method['sessID'] . ";";
$sql = "SELECT `athletes`.* FROM `events`
INNER JOIN `sets` ON `sets`.`EventID` = `events`.`EventID`
INNER JOIN `timetables` ON `timetables`.`SetID` = `sets`.`SetID`
INNER JOIN `times` ON `times`.`TableID` = `timetables`.`TableID`
INNER JOIN `athletes` ON `athletes`.`ID` = `times`.`AthleteID`
WHERE `events`.`EventID` = ?
AND `times`.`TimeID` IN(
SELECT MIN(`TimeID`)
FROM `times`
WHERE `TableID` IN(
SELECT `TableID`
FROM `timetables`
WHERE `SetID` IN(
SELECT `SetID`
FROM `sets`
WHERE `EventID` = ?
)
)
GROUP BY `AthleteID`
)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $sessionid, $sessionid);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$row = $result->fetch_assoc(); // fetch data
// do other things you want , such as echo $row['fieldname1'];

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.

PHP/MySQL select query issues

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.

Call to a member function rowCount() on a non-object

Im having a problem with my query. I recently switched to PDO, which is kind of new to me. Now i need to use JOIN in my query to get data from another table without making two executions.
Problem is, i get this error:
Call to a member function rowCount() on a non-object
I don't understand what the problem is. This is how my code looks like:
$friends_string = "SELECT * FROM `friends` as F, `users` as U WHERE `F.userID` = '$sess_user' AND `F.request` = '0' AND `F.friendID` = 'U.id'";
$friends = $db->query($friends_string);
if ($friends->rowCount() > 0) {
while($row = $friends->fetch(PDO::FETCH_ASSOC)) {
echo "<br /><a href='profile.php?id={$row["id"]}'>{$row["friendID"]}</a>";
}
} else {
echo "no Friends";
}
Or for short, just the query:
SELECT * FROM `friends` as F, `users` as U WHERE `F.userID` = '$sess_user' AND `F.request` = '0' AND `F.friendID` = 'U.id'
What I want is, get all rows from friends where userID is session and request is 0. But then i want to get the ID of those friends in users so i can make a link to their profile. Note the $row["id"]
I appreciate any feedback, doesn't have to answer my questions, if you note any problem please comment it. Thanks!
Don't put back ticks around the `table.field` ... You have to put them around `table`.`field`
Change your query with this one:
$query = "SELECT * FROM `friends` as F INNER JOIN `users` as U ON `F.friendID` = `U.id` WHERE `F.userID` = '{$sess_user}' AND `F.request` = '0'";
And add this to your connection, it will show you the errors:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception
IMHO!
I saw problems like that with PDO...
and...
i think it's more likely to do all with pure SQL but good then duck your head with PDO.

Joining multiple tables in mySQL

Okay, I'm not that good at mySQL.
What I'm trying to do here is join 2 tables:
1. users
2. comments
I'm trying to make a comment system where it should pull the username and profile picture from users table and the comments and date_posted from the comments table.
Here is my query:
$mem_query = mysql_query("SELECT `comments`.`comment_id` AS `comments_id`, `users`.`user_id` AS `users_id`, `users`.`username`,`users`.`profile_pic`,`comments`.`txt_content`,`comments`.`date_posted` FROM `comments` INNER JOIN `users` ON `users`.`user_id` = `comments`.`user_id` WHERE `comments`.`post_id` = '$post_id'");
And I want to run the query using the while loop:
while($run_mem = mysql_fetch_array($mem_query)){
$comment_id = $run_mem['comments_id'];
$txt_content = $run_mem['comments.txt_content'];
$profile_pic = $run_mem['users.profile_pic'];
?>
//Run all the comments depending upon the post_id.
<?php
}
?>
As of now, it is giving me this error: - THIS IS NOT SHOWING AFTER my 2nd update.
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\simpleblog\view.php on line 73
How do I fix it? Thanks.
P.S: I know 'mysql_query' is being deprecated in PHP. I'll change that later.
P.S 2: I fixed the query from table.column to table.column, however, its not showing any errors but its not pulling any information from the database.
Look at the ` symbols, they should look like:
`table`.`column`
and not:
`table.column`
there is a big syntax error in your query:
SELECT `comments.comment_id` AS `comments_id`, `users.user_id` AS `users_id`, `users.username`,`users.profile_pic`,`comments.txt_content`,`comments.date_posted` FROM `comments` INNER JOIN `users` ON `users.user_id` = `comments.user_id` WHERE `comments.post_id` = '$post_id'
should be
SELECT `comments`.`comment_id` AS `comments_id`, `users`.`user_id` AS `users_id`, `users`.`username`,`users`.`profile_pic`,`comments`.`txt_content`,`comments`.`date_posted` FROM `comments` INNER JOIN `users` ON `users`.`user_id` = `comments`.`user_id` WHERE `comments`.`post_id` = '$post_id'
you wrote this: `comments.user_id` but it has to be this: `comments`.`user_id` and that at almost every position where you did that wrong
http://www.php.net/manual/en/function.mysql-query.php
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
Looks like the latter happened. An error occurred and the mysql_query call returned false.

Categories