Joining multiple tables in mySQL - php

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.

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'];

SQL Error returned in php for query with joins

I am trying to populate a table by executing the below query for a php application:
$sql3 = "SELECT distinct(`t1.testName`), `t2.comments AS C1` from `sample AS t1` left join `sample AS t2` ON `t1.testName`= `t2.testName` where `t1.buildNumber`= 181 and `t2.buildNumber`= 180 and `t1.errorStackTrace` is not null";
$result3 = mysqli_query($dbconnect,$sql3);
if(!mysqli_query($dbconnect, $sql3)){
printf("error message: %s\n",mysqli_error($dbconnect));
}
I am seeing the following error returned:
error message: Table 'testdata.sample as t1' doesn't exist
I have tried a lot to fix this but couldn't. The query runs fine when run on mysql.
Any help would be appreciated.
Thanks
You have to use the backticks only arround table names or column names not including the alias:
$sql3 = "SELECT distinct(`t1`.`testName`), `t2`.`comments` AS C1 from `sample` AS ` left join `sample` AS t2 ON t1.testName= t2.testName where t1.buildNumber= 181 and t2.buildNumber= 180 and t1.errorStackTrace is not null";
You are escaping the table name incorrectly. Use this raw query:
SELECT DISTINCT(t1.testName),
t2.comments AS C1
FROM `sample` AS t1
LEFT JOIN `sample` AS t2
ON t1.testName = t2.testName
WHERE t1.buildNumber = 181 AND
t2.buildNumber = 180 AND
t1.errorStackTrace IS NOT NULL
I don't think you really need backticks anywhere. But in any case, only column names need to be backticked, never aliases, e.g.
t1.`testName` but NOT `t1.testName`
Wrong back quote, try this:
$sql3 = "SELECT distinct(t1.`testName`), t2.`comments` AS C1 from `sample` AS t1 left join `sample` AS t2 ON t1.`testName`= t2.`testName` where t1.`buildNumber`= 181 and t2.`buildNumber`= 180 and t1.`errorStackTrace` is not null";

Can't insert query result into table using PHP

I am trying to insert some information to a new table in my database. For this I query information from two tables and a xref table, then I try to do the insert as I usually do. This is not working.
Here is the code,
$query = "select listaA.product_s_desc, category_name, listaA.product_desc, listaA.product_sku
from listaA, jos_vm_category, jos_vm_product_category_xref
where listaA.product_id = jos_vm_product_category_xref.product_id
and jos_vm_category.category_id = jos_vm_product_category_xref.category_id limit 10";
$result = mysql_query($query);
$row = mysql_fetch_array($result) or die;
do{
$imagen = 'http://accesoriosazteca.mx/imagesite/'.$row['listaA.product_sku'].".png";
mysql_query("insert into lista_importat (id, activo, sku, nombre, categoria, descripcion_corta, descripcion_larga, pedidos, mostrar_precio, imagen)
values ('$row['listaA.product_id']', '1', '$row['listaA.product_sku']', '$row['listaA.product_s_desc']', '', '$row['listaA.product_s_desc']', '$row['listaA.product_desc']', '0', '0', '$imagen')");
}while($row = mysql_fetch_array($result));
With the code above I get a blank screen, and nothing is inserted into the new table. Any ideas?
If the query starting...
select listaA.product_s_desc, ...
returns a resultset, the first column in the resultset will have a column name of product_s_desc, not listaA.product_s_desc.
(Running the query in the mysql command line client will demonstrate this behavior.)
To reference to the value of that column in $row:
$row['product_s_desc']
Note that the query does not return a column with a name of listaA.product_id.
A few notes, beyond answering the question you asked:
For the benefit of readers, I recommend you ditch the old school comma syntax for the join operation and use the JOIN keyword in it's place, and relocate the join predicates from the WHERE clause to an ON clause. I also recommend the use of short table aliases, and also qualifying ALL column references. For example:
SELECT a.product_s_desc
, c.category_name
, a.product_desc
, a.product_sku
FROM listaA a
JOIN jos_vm_product_category_xref r
ON r.product_id = a.product_id
JOIN jos_vm_category c
ON c.category_id = r.category_id
ORDER BY 1
LIMIT 10

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

Mysql query for using count on a view in php

I have a query:
$result = mysql_query("CREATE VIEW temporary(IngList) AS (
SELECT DISTINCT (r1.Ingredient)
FROM recipes r1,
recipes r2
WHERE r1.Country = '$temp'
AND r2.Country = '$temp2'
AND r1.Ingredient = r2.Ingredient)
SELECT COUNT(*) FROM temporary");
I want the query to make a view called temporary and have it return a count of the number of rows in the view temporary. I know this code works without the SELECT COUNT(*) because I checked my database and the view is created.
Yet this code throws the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT COUNT(*) FROM temporary' at line 1
I checked the syntax and it seems to be correct. What seems to be the problem because its quite frustrating.
From the mysql_query documentation:
mysql_query() sends a unique query (multiple queries are not supported)...
You can't create the view, and select from it in a single mysql_query. The view is unnecessary:
$sql = sprintf("SELECT COUNT(DISTINCT r1.Ingredient)
FROM recipes r1
WHERE r.country = '%s'
AND EXISTS(SELECT NULL
FROM recipes r2
WHERE r2.Country = '%s'
AND r1.Ingredient = r2.Ingredient)",
$temp, $temp2);
$result = mysql_query($sql);
For starters you have two statements. What you're writing looks more like a stored procedure. Even if it worked, you would need a semicolon at the end of the first statement. And another statement somewhere saying "DROP VIEW ...." when you are done.
And a temp view is a bit of a non sequitur. I can't find any reference to "CREATE VIEW temporary". Or maybe it's to create a view named temporary with an argument? Views don't take arguments.
I think you might get what you want with a semi-simple SQL statement something like:
$result = mysql_query(
"SELECT COUNT(DISTINCT r1.Ingredient)
FROM recipes r1
JOIN recipes r2 ON r1.Ingredient = r2.Ingredient
WHERE r1.Country = '$temp'
AND r2.Country = '$temp2'");

Categories