Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I want to display certain data from tableA in the database, but only the ones which have similar location as the user from tableB, who is logged in.
I am using the code below, but I get the following error: Unknown column 'Amsterdam' in 'where clause'.
The code I am using is:
$query = 'SELECT * FROM tableA WHERE `city` LIKE '.$user['city'].' ORDER BY `id` DESC';
$result = mysql_query($query, $conn) or die(mysql_error());
$row_result = mysql_fetch_assoc($result);
echo $row_result['name'];
What do you think might be the error?
You need to concatenate the value of $user['city'] with single quotation marks.
Assuming the city is Amsterdam, what you are aiming for is a SQL statement that reads:
SELECT * FROM tableA WHERE `city` LIKE 'Amsterdam' ORDER BY `id` DESC
but what you are generating is:
SELECT * FROM tableA WHERE `city` LIKE Amsterdam ORDER BY `id` DESC
so MySQL is treating the name of the city as a table column, because it is not enclosed.
Your code needs to be:
$query = "SELECT * FROM tableA WHERE `city` LIKE '".$user['city']."' ORDER BY `id` DESC";
$result = mysql_query($query, $conn) or die(mysql_error());
$row_result = mysql_fetch_assoc($result);
echo $row_result['name'];
The above example used double-quotes to enclose the static text, but you can use single-quotes by escaping the ones that need to form the string value:
$query = 'SELECT * FROM tableA WHERE `city` LIKE \''.$user['city'].'\' ORDER BY `id` DESC';
city is a text field. Therefore the SQL parser expects text, which has to be in quotes.
"'.$user['city'].'"
You may want to put additional quotes around $user['city'] as below:
$query = 'SELECT * FROM tableA WHERE `city` LIKE `'.$user['city'].'` ORDER BY `id` DESC';
As others have noted, you're missing the quote marks around $user['city']
Aside from that, can I recommend that you stop using the mysql_ functions as they've been deprecated.
If you move to mysqli_ or PDO:: calls, you open up the possibility of using prepared statements which will make life a lot easier and may actually give you cause to think "How did I ever cope without these?"
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So i end up with lots and lots of queries.
Im wondering if you can just run 1 query to get all the info you require for said page.
And then later use php to more or less split the query into different once like if you where to use the WHERE clause in SQL.
My case
I want to get the number of rows for 2 different tasks but from the same table.
1 being where the id is filtered and the other where lets say the user is filtered.
How i typically do it is just make 2 queries and use the where clause to so define the 2.
It just seems rather inefficient to me to make more queries while they all come from the same table.
If there is a way to achieve this that would be awesome to know, I did some tries my self but thus far failed to succeed.
Fiddled around with multidimensional arrays.
Example
$sql = "SELECT * FROM table1 WHERE type = 'type7' ORDER BY date DESC LIMIT 5";
$result = mysqli_query($conn, $sql);
$var = mysqli_fetch_all($result, MYSQLI_ASSOC);
$sql = "SELECT * FROM table1 WHERE type = 'type2' ORDER BY date DESC LIMIT 5";
$result = mysqli_query($conn, $sql);
$var1 = mysqli_fetch_all($result, MYSQLI_ASSOC);
$sql = "SELECT * FROM table1 WHERE type = 'type5' ORDER BY date DESC LIMIT 5";
$result = mysqli_query($conn, $sql);
$var2 = mysqli_fetch_all($result, MYSQLI_ASSOC);
Since its going to be taken from the same table anyways why have multiple queries just to filter it?
This is a pretty broad question and the most basic answer is not language-specific, i.e. it's true of PHP, Java, and other languages.
Imagine you have a page that displays all banking transactions. You would have a SQL statement along the lines of:
SELECT * FROM transactions
If you then wanted to display only a subset of these, you could simply use code (PHP/Java) to filter them and display the result. For instance, in Java you would use lists to store the entire data and streams to filter the ones you want to show. In PHP, you would use array maps.
But your approach has issues: you are going to be selecting a lot more data than need be (most likely). This won't perform well and you will hit UX issues such as pagination.
You can query everything at once and then filter with php using foreach. But I'd guess that is slower then the 2 queries.
Having two queries is not inefficient. Actually it is using the (usually very fast Database) how it is intended to.
If speed is a factor you could always combine your queries into one using subselects.
SELECT ( SELECT COUNT(*) FROM user WHERE name LIKE 'john%'), ( SELECT COUNT(*) FROM user WHERE id < 3)
Alternatively you could set up a (slow) view or have a database trigger that updates the counts in a type of caching table.
Honestly this is probably the wrong place to optimise.
You can do this in one query. Something like this:
select count(*) as total,
sum( <filtering conditions here> ) as filtered_total
from t;
MySQL treats boolean values as numbers with 0 for false and 1 for true, so the sum() counts the number of true values.
you can use UNION or UNION ALL
for example
SELECT userName, mail
FROM user
WHERE mail like '%gmail.com%'
UNION ALL
SELECT userName, mail
FROM user
WHERE userName like '%john%'
to remove duplicates use only UNION
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 1 year ago.
I have a problem with my php code when i try to choose a string in my database.
Well, I have a table "news" and a field "category" (TINYTEXT type) there. And I try to display a string from this table by using "where clause":
$Sql = 'SELECT * FROM `news` WHERE `category` = '.$Param['category'].' ORDER BY `id` DESC';
I must say that I received "$Param['category']" by using URL Path: 1
So, if my "category" value of any string in table has any string type value like "games" 2, 3 - string from my table isn't displayed with this error "Fatal error: Uncaught mysqli_sql_exception: Unknown column 'games' in 'where clause'"
But, if I change the "category" value of string in the database into anything numeral value - the string from my table is displayed correctly!4, 5
What's wrong with my code? Thank you in advance! Sorry for the mistakes.
You need to use prepared queries, both for the sake of SQL injection protection, and because it will fix your bug. I believe the issue is that you don't have any quotes at all around your parameters. As a result you're building queries like this:
SELECT * FROM `news` WHERE `category` = games ORDER BY `id` DESC
SELECT * FROM `news` WHERE `category` = 1 ORDER BY `id` DESC
The latter is a valid query: mysql looks for records where the category is 1. The former is not: the query tries to find records where the column category matches the column games. The latter doesn't exist so you get an error. You want to build these queries:
SELECT * FROM `news` WHERE `category` = 'games' ORDER BY `id` DESC
SELECT * FROM `news` WHERE `category` = '1' ORDER BY `id` DESC
Which you would do with this code:
$Sql = "SELECT * FROM `news` WHERE `category` = '".$Param['category']."' ORDER BY `id` DESC";
(note that I switched to double quotes and included single quotes around the input parameter). BUT THIS IS STILL WRONG as it leaves you extremely vulnerable to SQL Injection, which would allow an attacker to potentially download or modify your entire database. Take the time to read up and learn how to use prepared queries, which is both more secure and also would have prevented this bug in the first place.
Others have suggested you use parameterized queries. That's good advice, but they didn't show you what it looks like (not that it's hard to find examples).
Here's a quick example using PDO:
$Sql = 'SELECT * FROM `news` WHERE `category` = ? ORDER BY `id` DESC';
$stmt = $pdo->prepare($Sql);
$stmt->execute([ $Param['category' ]);
This executes the query as if you had put $Param['category'] into the SQL, but it does it completely safely, even if the value contains special characters.
You don't put quotes around the ? placeholder. It's implied that the query will treat it as a single scalar value, not a column name. In fact, you can use parameters only for values — not for column names, or expressions, or SQL keywords or anything else.
Writing code using query parameters is easier than not using parameters, because it makes your code easier to write and easier to read.
You have to put quotes around any string in the query if it is not a field in the table. Try this:
$Sql = "SELECT * FROM `news` WHERE `category` = '".$Param['category']."' ORDER BY `id` DESC";
As was mentioned if you are pulling in that string from a source where you have to word about code injection you should use prepared statements or PDO.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to develop php page but I have a problem, I would like to get data from data base without duplicate.
$tsql = "SELECT COUNT(ID) FROM FactoriesViolations";
$rowsPerPage = 25;
$stmt = sqlsrv_query($conn, $tsql);
please help me.
thanks in advance.
what all columns are you expecting in your output. If its only ID
$tsql = "SELECT COUNT(DISTINCT(ID)) FROM FactoriesViolations";
if you want all the columns from the table and eliminate the duplicate records
this query will do the needful.
SELECT Col1, Col2,... ColN FROM FactoriesViolations GROUP BY Col1, Col2,... ColN;
here Col1, Col2,... ColN are column names of your FactoriesViolations table.
Use below query. It will work.
$tsql = "SELECT COUNT(DISTINCT ID) FROM FactoriesViolations";
use below way for count of unique records
SELECT COUNT(DISTINCT column_name) FROM FactoriesViolations; // column_name is column which contains duplicate
DISTINCT keyword tells the server to go through the whole result set and remove all duplicate rows after the query has been performed.
Format :
SELECT DISTINCT *
FROM TABLE_NAME
WHERE CONDITION(S)
In your case, the following query should work
$tsql = "SELECT COUNT(DISTINCT(ID)) FROM FactoriesViolations" ;
This will return the count of all unique IDs existing in the table.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Consider the following script:
SELECT * FROM TABLE1 WHERE COLUMN1='$exb';
$exb is a PHP variable which is fed from an HTML select list with 3 values:0,1,2. Values 1 and 2 correspond to column1 values. In case of selecting value 0, I want to include all the values of COLUMN1. Is there a way to implement the above without changing the script? In other words is there any keyword to assign to $exb which will oblige the script to select all the rows of table TABLE1 in case the user selects 0 from HTML select list?
Thank you
It's a little unclear, but I think you are asking is there a special clause you can add to a where clause to return every single row from the database rather than specific criteria matched in a where clause.
You can put in a pretend where clause by saying col1=col1 which is effectively a bogus (though valid) syntax like this:
SELECT * FROM TABLE1 WHERE COLUMN1=column1;
Though it would have to be without the quotes to select every single row of the table.
Putting the quotes around the variable would be very simple in your php however.
Having said that, wouldn't it be much easier to simply omit the where clause entirely if the value selected is 0?
For this you require to build a dynamic query.
$query = "SELECT * FROM TABLE1";
$exb = isset($_GET['exb']) ? $_GET['exb'] : 0;
$goodParam = array(0,1,2);//array of allowed values
if($exb>0){
if (in_array($exb, $goodParam)) {
$query .= " WHERE COLUMN1 = '$exb'";
}
}
echo $query;
I don't think you can do that with MySql query only. You need to use php and ifelse statement where you can check for $exb value before executing query. For example:
if($exb == "0")
$query = "SELECT * FROM TABLE1";
else
$query = "SELECT * FROM TABLE1 WHERE COLUMN1='$exb'";
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I want to do a query by adding a "OR" statement. Using what i have below won't show all entries. What am i doing wrong?
//$q = search variable;
$sql = "SELECT name, id_code from codes WHERE (id_code = '$q') OR (name='$q')";
$sql = "SELECT name, id_code from codes WHERE (id_code = '$q') OR (name='$q')";
$sql = "SELECT name, id_code from codes WHERE (id_code = '$q' OR name='$q')";
$sql = "SELECT name, id_code from codes WHERE id_code = '$q' OR name='$q'";
All of these will produce the same result.
Have you tried SELECT name, id_code from codes WHERE id_code = '$q' OR name='$q' (i.e. without the parentheses)?
This code is correct. The reason why it doesn't work is because the needle hasn't been found in the haystack.
This may be because the id_code column its a numeric column, or the values of the column are zero padded or the variables aren't been passed to the query.
Check the variables to see if they are being passed by echoing the query and take a look at the data type of the fields.
If a field is numeric, it can be assigned or compared without the quotes.
Also, if you want to search part of the name column, you will have to change the = operator to a like operator:
$sql = "SELECT name, id_code from codes WHERE (id_code = '$q') OR (name like '%$q%')";
The % means anything (zero or more chars), so the query will look for any name starting with anything, then your search therm and then ending with anything.