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.
=)
Related
How do I make it pick all results that are not equal to the $var , here's my code.
$opti=mysql_query("SELECT * FROM table1 WHERE imageid=$image_id");
while ($vari = mysql_fetch_array($opti)) {
$var = $vari['tagid'];
$options=mysql_query("SELECT * FROM table WHERE id!=$var");
while ($taghe1 = mysql_fetch_array($options)) {
$tagname = $taghe1['name'];
echo "".$tagname.", ";
} }
Try:
$options=mysql_query("SELECT * FROM table WHERE id<>{$var}");
You can probably see from the answer you accepted that adding the quotes solved your problem. Another way to do this is to just use one query. I will show an example using mysqli instead of the deprecated mysql, but the same query should work in mysql if you must use it. I added a couple of other suggestions that aren't really addressing your question, but make me feel better about my answer.
// Please be sure to escape $image_id before using it like this
$unused_tags = mysqli_query($db, "SELECT `name` FROM `table` AS t
LEFT JOIN (SELECT tagid FROM table1 WHERE imageid=$image_id) AS t1
ON t.id = t1.tagid WHERE t1.tagid IS NULL;");
while ($tag = mysqli_fetch_array($unused_tags)) {
$tags[] = htmlspecialchars($tag['name']); // escape your output
}
echo implode(", ", $tags); // doing it this way eliminates the trailing comma
You could use this:
$options=mysql_query("SELECT * FROM table WHERE id not in ('$var')");
You could have multiple values here, e.g.
$options=mysql_query("SELECT * FROM table WHERE id not in ('$var1', '$var2', '$var3')");
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.
Im trying to pass an array that I already found by a query into another query. For example:
$first_query = "SELECT id FROM from Table WHERE user = '{$_SESSION['id'}'";
$result = mysql_query($first_query,$connection);
$ids = mysql_fetch_array($result);
This is where it gets tricky for me. I want to pass $ids into the next query.
$id_implode = implode(", ", $ids)
$second_query = "SELECT * FROM Table2 WHERE id = '{$id_implode}';
The second query doesnt seem to be working. Any help is greatly appreciated!
your second query's syntax is wrong. Once evaluated it should read
select * from Table2 where id in (1,2,3)
ditch the curly braces and change the = to in. Don't use OR - that's a dumb way of ignoring good sql functionality
EDIT: Teneff's comment makes a very good point - why are you approaching the problem in this way? If there is a relationship between the tables they can be joined and all the data you want can be retrieved in a single query. If for some reason you can't / won't join the tables you could at least try a sub-query
select * from table2 where id in (select id from table where user = $_SESSION['id']);
To use a where statement with multiple entries to match on, use in ().
$id_implode = "'".implode("', '", $ids)."'"
$second_query = "SELECT * FROM Table2 WHERE id in ({$id_implode});
I think you should use IN
$id_implode = implode(", ", $ids)
$second_query = "SELECT * FROM Table2 WHERE id IN '({$id_implode})';
This assumes that $ids is made of int of course, otherwise you have to enclose eache entry in quotes. that means
IN (6,7,8,9)//this doesn't need quotes
IN ('lemon', 'orange')//needs quotes
try to use the IN syntax:
$id_implode = implode("', '", $ids);
$second_query = "SELECT * FROM Table2 WHERE id in ('{$id_implode}');
if (isset($_SESSION['user_tz'])) {
$posted = "CONVERT_TZ(p.posted_on, 'UTC', '{$_SESSION['user_tz']}')";
} else {
$posted = 'p.posted_on';
}
// Run the query:
$q = "SELECT t.subject, p.message, username, DATE_FORMAT($posted, '%e-%b-%y %l:%i %p') AS posted FROM threads AS t LEFT JOIN posts AS p USING (thread_id) INNER JOIN users AS u ON p.user_id = u.user_id WHERE t.thread_id = $tid ORDER BY p.posted_on ASC";
I changed the $posted in the query to a plain "posted_on" which returned the time, I also tried some wrapping it in '' and "" but those ended up breaking it entirely; for future reference I'd like to know why that variable isn't getting passed through to the query. It's probably something really simple and I'll feel silly but help would be appreciated greatly.
Thanks.
NULL is a valid value for isset() to trigger TRUE. Use unset($_SESSION['user_tz']);
It seems to me that the way you have it written, it is using $posted as the value to pass to the date_format. What you really want is the contents of $posted so you need to close quotes around it and concatenate the value into the $q string.
When I run the code below when $entry = miami.com, I get the following error message:
SELECT COUNT(*) FROM #&*+ WHERE `site`
LIKE 'miami.com':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 '' at line 1
It looks like I'm not correctly defining $table. Any ideas how I could do that?
Thanks in advance,
John
$result = mysql_query("SHOW TABLES FROM feather")
or die(mysql_error());
while(list($table)= mysql_fetch_row($result))
{
$sqlA = "SELECT COUNT(*) FROM $table WHERE `site` LIKE '$entry'";
$resA = mysql_query($sqlA) or die("$sqlA:".mysql_error());
list($isThere) = mysql_fetch_row($resA);
if ($isThere)
{
$table_list[] = $table;
}
}
if it were me debugging that i would see what
print_r(mysql_fetch_row($result));
outputs
I think you are using the list-language construct incorrectly:
Description
void list ( mixed $varname [, mixed $... ] )
Like array(), this is not really a function, but a language construct. list() is used to > assign a list of variables in one operation.
Example:
$info = array('coffee', 'brown', 'caffeine');
// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";
Now, what you are trying to do is to fetch dynamic table-names (it seems). You do not need to use the list-function, since you can access the result as an array (you can define the appropriate indexes of the array that you are interested in and only assign them, but I think array access is much clearer):
while($row = mysql_fetch_assoc($result))
{
$sqlA = "SELECT COUNT(*) FROM ${row['table']} WHERE `site` LIKE '$entry'";
[...]
}
I am a bit curious though, do ALL the tables in your database feather have a column named site? Otherwise this query will fail, no matter how you format or refactor your code.
Actually, I recently recalled that my
very first table name is indeed
"#&*+." I added it deliberately during
development
And you're wondering why your SQL fails? :)
Quote your table name because this one is by far not a table name that can be used literally.
Something like
"SELECT COUNT(*) FROM \"$table\" ...
i think need to add MYSQL_ASSOC
to line that do the loop
mysql_fetch_row($result,MYSQL_ASSOC)
the default is : MYSQL_BOTH
what mean that in the php loop you get the entry of the table name ,
and the entry of index like 0,1,2,...
I am pretty sure your SHOW TABLES query is returning garbage. I was able to reproduce your problem by copying an existing table_name.frm to #&#.frm in the data folder for a local database. Make sure your database is not corrupt (meaning, try repair): http://dev.mysql.com/doc/refman/5.1/en/repair-table.html
I think this is what you're after:
$result = mysql_query("SHOW TABLES FROM feather") or die(mysql_error());
while($table_row = mysql_fetch_row($result))
{
$table = $table_row[0];
$sqlA = "SELECT COUNT(*) FROM `" . mysql_escape_string($table) . "` WHERE `site` LIKE '" . mysql_escape_string($entry) . "'";
$resA = mysql_query($sqlA) or die("$sqlA:".mysql_error());
$isThere_row = mysql_fetch_row($resA);
$isThere = $isThere_row[0];
if ($isThere)
{
$table_list[] = $table;
}
}
NOTE: variables inside your sql should be escaped. I don't use mySQL but I assume mysql_escape_string should work. There is another function, mysql_real_escape_string, that might be more appropropriate. You may want to read the docs for that.