How to use a PHP variable in Inner Join MYSQL query? - php

I have been trying for the past day to get mysql to recognize my PhP variable, but I have had no luck so far.
The code:
...connect to db...
session_start();
//Calls up Session stored variable
$currentUsr= $_SESSION['username'];
//SQL Query
$sql= 'SELECT Users.Username, books.* FROM Users
INNER JOIN UserLinkBooks lb
ON Users.Username = lb.Username
INNER JOIN Books
ON lb.bkTitle = books.Title
WHERE Users.Username = "$currentUsr"';
$result=mysqli_query($conn,$sql);
//Error Check
if (!$result) {
printf("Error: %s\n", mysqli_error($conn));
exit();}
//display row
while($row=mysqli_fetch_array($result)){
echo "<strong>".$row['Title']."</strong>".$row['Description']."</br>";}
My issue is that the $currentUsr is not properly calling the username that was passed. After doing an error check on it, it seems to be empty.
What I do not understand is that when I use the code :
$sql = "SELECT * FROM Users WHERE `Username`='$currentUsr'";
The variable is processed and works fine, calling up the book title's and description perfectly. Also, if I manually type in:
WHERE Users.UserName = "Bill"';
It works fine.
Some of the other errors I've gotten from various attempts are:
WHERE Users.UserName = '.'$currentUsr';
Error: Unknown column '$currentUsr' in 'where clause'
or
WHERE Users.UserName = '.$currentUsr;
Error: Unknown column 'Bill' in 'where clause'
Any help would be greatly appreciated. Thanks

Your variable is in a single quoted string, preventing interpolation. You can try:
$sql = "SELECT Users.Username, books.* FROM Users
INNER JOIN UserLinkBooks lb
ON Users.Username = lb.Username
INNER JOIN Books
ON lb.bkTitle = books.Title
WHERE Users.Username = '" . $currentUsr ."'";
Using concatenation makes the code more readable in my opinion. Having said that, you should look into using parameterized queries as they cut down on injection issues. Mysqli has such capabilities.

When you're using variables inside strings, you should put these strings within double, not single quotes, otherwise the variables are not replaced with their values.
Also check this question: What is the difference between single-quoted and double-quoted strings in PHP?

If you use double quotes, then put your variables in curly braces - else use Concatinatoin with the dot.

Related

mysqli and passing a query as parameter - no results

This is my code:
$sql = $_POST['sql'];
....
$result = $mysqli->query($sql);
This does not return any results. So i echoed the $sql variable and this is the result:
SELECT o.entity_id, o.increment_id FROM sales_flat_order o JOIN sales_flat_order_payment p ON o.entity_id = p.parent_id JOIN sales_flat_order_address a ON o.entity_id = a.parent_id WHERE a.country_id = \'DE\' ORDER BY o.entity_id DESC LIMIT 10;
Now, when I assign this to the $sql variable directly, it works. What could be the problem?
Thanks
Well, first you could test $result and output the last error with $mysqli->error when it's false, that would give you details on what's wrong.
Secondly, you should NOT execute a query that's coming from POST or GET parameter, that's how you allow anyone to do anything on your database with sql injection. That's a big security breach.
Thirdly, the issue is probably on POST encoding (note the quotes \'DE\') so if you urldecode and/or stripslashes your $sql it would probably work

Sql inside php file

I am doing a sql query inside php file but i don´t know what Im doing wrong in the query. Perhaps I don´t concatenate properly the sql statement or I don't use properly the quotes, somebody can help me? Thank you. Here is my code:
$config['table_name'] = "peliculas";
$config['table_namedos'] = "opiniones";
$sql = "SELECT ".$config['table_name']." id_pelicula ".$config['table_name']." nombre ".$config['table_name']." caratula ".$config['table_name']." duracion ".$config['table_namedos']." nick ".$config['table_namedos']." minuto "." INNER JOIN ".$config['table_namedos']." ON ".$config['table_name']." id_pelicula =".$config['table_namedos']." id_pelicula";
You need to seperate each selected columns with a comma in the query which you are missing and also while doing the concatanation you are giving some space after the colname. fieldname.
Also missing the from table name
so it should be as
$sql = "SELECT
".$config['table_name'].".id_pelicula,
".$config['table_name'].".nombre,
".$config['table_name'].".caratula,
".$config['table_name'].".duracion,
".$config['table_namedos'].".nick,
".$config['table_namedos'].".minuto from
".$config['table_name'].
" INNER JOIN ".$config['table_namedos']." ON ".$config['table_name'].".id_pelicula =".$config['table_namedos'].".id_pelicula";
Try it this way You missed the dots between tablename and columnname, also you need FROM and you need to seperate columns by comma
<?php
$sql = "SELECT
{$config['table_name']}.id_pelicula,
{$config['table_name']}.nombre,
{$config['table_name']}.caratula,
{$config['table_name']}.duracion,
{$config['table_namedos']}.nick,
{$config['table_namedos']}.minuto
FROM
{$config['table_name']}
INNER JOIN
{$config['table_namedos']}
ON
{$config['table_name']}.id_pelicula = {$config['table_namedos']}.id_pelicula";
If you do not like the { } syntax you can also do it this way
<?php
$t1 = $config['table_name'];
$t2 = $config['table_namedos'];
// or in one statement: list($t1, $t2) = array($config['table_name'], $config['table_namedos']);
$sql = "SELECT
$t1.id_pelicula,
$t1.nombre,
$t1.caratula,
$t1.duracion,
$t2.nick,
$t2.minuto
FROM
$t1
INNER JOIN
$t2
ON
$t1.id_pelicula = $t2.id_pelicula";
If you are really really fond of string . concatenating, I advise using ' instead of " and also leave spaces around the . operator so you can see better where . is part of the String and where it is the operator.
I have had the same problem and what I did was assign it to a string {ex: $stringname} then use the string in the query.
So
$stringtablename = $config['table_name'];
$sql = "SELECT ".$stringtablename; ect.
I'm sure you get the point with out me writing the whole thing out.
=)

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 php join statement

I am not sure if that join statement is writen in the right way:
<?php
function generateComment($commentID)
{
$avatar_Q=mysql_query("
SELECT * FROM comments com
INNER JOIN users us ON com.user_id=us.user_id
WHERE comment_id=$commentID // will that $commentID be red in that query string or will it treat it as a string "commentID"
");
if($row=mysql_fetch_array($avatar_Q))
{
$userName=$row["us.user_name"]; // do I refer to the fields like that
$avatarPath=$row["us.avatar"];
$avatarRep=$row["us.reputation"];
$message=$row["com.comment"];
$date=$row["com.date"];
}
mysql_close();
if(!isset($avatarPath))
{
$avatarPath="blank picture";
}
?>
Is this the most efficient way to write a join statement
Your query is written correctly, but you can improve it by specifing the table on comment_id, and for a better returning I suggest you to specify with column you want back, also I will use the variable outside the "string", because it's a numeric value (I suppose you omit the single quote like...
$sql = "Select com.command_it, etc
FROM ..... WHERE com.comment_id = ".$commentID."";
If otherwise the com.comment_id is text or varchar you must use the single quote like:
$sql = "Select com.command_it, etc
FROM ..... WHERE com.comment_id = '".$commentID."'";
Moreover this way you get only the rows where there is a user and a comment, if one user have no comment you don't retrieve that user...
If you want the user also if he has no comments you must use a LEFT JOIN
$sql = "SELECT com.comment_id, etc FROM users us
LEFT JOIN comments com ON com.user_id=us.user_id
WHERE com.comment_id=".$commentID."";
Not sure what you're doing with this line
WHERE comment_id=$commentID // will that $commentID be red in that query string or will it treat it as a string "commentID"
");
But you need to specify which table comment_id is coming from, say comments, then you might do something like
$avatar_Q=mysql_query("SELECT * FROM comments com
INNER JOIN users us ON com.user_id=us.user_id
WHERE com.comment_id=$commentID");
Not sur if it's the best way, but you could try to mysqlslap a mysql DB with it. Compare it with left join and other types of join and see which one is the best in your case. MySQL is all about slapping.

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