simple mysql select and insert not working - php

I have no idea why this isn't working. I've taken code from a previous project that works fine. I just want to select specific columns. Here's what im trying...
$result = mysql_query("SELECT when, where, name FROM tablename ORDER BY count DESC LIMIT 0, 20");
//I dont really know how to debug php well, so this is all I have to go by to know if its not working.
if (!$result)
{
echo "<p>Page load has failed please try again</p>";
}
if I select all like this it works fine:
$result = mysql_query("SELECT * FROM tablename ORDER BY count DESC LIMIT 0, 20");
If im doing an insert, that doesn't work either...
$query = "INSERT INTO tablename (when, where, name) VALUES ('$when' , '$where' , '$name');";
mysql_query($query);
I'm sure the spelling is correct i've looked at it several times, and even if I put
echo $row["name"]; and the others ect while using the select all * they appear...
It just seems like its happening when im selecting individual columns.
I have other tables, with other sites using the same exact code and its working fine.
How can i fix this? or at least how can i debug the php to get some better error messages?
edit:
I'm sure the values going in are good, its just simple helloworld string
I've tried including count in the select incase that needed to be there for the sort, but that didnt make it work.

The word where is a reserved word (the WHERE clause of SELECT, UPDATE and DELETE queries). So is when. count is a built-in function name but can be used as an identifier, though you shouldn't.
If you use it as an identifier, you must always enclose it in `backticks` in the query. I recommend not using parts of the query language as column names.
http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html

WHERE, WHEN and COUNT are reserved MySQL words (http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html). Use backticks like this.
$result = mysql_query("SELECT `where`, `when`, name FROM tablename ORDER BY `count` DESC LIMIT 0, 20");

where is a reserved sql word, use tablename.where to select the correct column.

Related

MySQL: Query with ORDER BY clause returns nothing

In my MySQL database, I have a table called pages and it contains several columns, two of which are order (int), tab (int), and name (text). When I call a query as such
"SELECT * FROM pages WHERE tab = '$tid'"
it executes with no problem, returning all rows with the correct tab label. The problem I am having is when I execute with an ORDER BY :
"SELECT * FROM pages WHERE tab = '$tid' ORDER BY order ASC"
I get a return of false from the query. No errors either.
When I put the column order in single quotes ', the query works like it did before, but applies no order.
Why am I getting no return regardless of which column I try to sort by? How do I make my query sort to a column correctly?
ORDER is a reserved word in MySQL, so you should escape it with backticks ` if you want to use it as an identifier :
SELECT * FROM pages WHERE tab = '$tid' ORDER BY `order`
You are getting an error is not coming out. Try the following:
select * from pages order by `order`;
ORDER is a reserved word. If you not quote it properly the query will not run.

Error in query syntax

i am using ORDER BY in mysql SELECT query but i dont know ots not ordering the data.. if i use this query its showing the table but not ordering the data in ascending order
$result = mysql_query("SELECT *FROM learningmaterial ORDER BY 'order' ASC")or die(mysql_error());
but if i use
$result = mysql_query("SELECT *FROM learningmaterial ORDER BY order ASC")or die(mysql_error());
then it give error that the syntax of the query is not right...i've seen on various sites but i couldnot found anything unique in my code...i think its right,...please check the query and mend a solution. Thankx in advance :)
You need backticks, not single quotes (a):
... SELECT * FROM learningmaterial ORDER BY `order` ASC ...
By using single quotes, you're ordering the rows by a constant (each row gets the same constant) so effectively not ordering them at all.
By using a "naked" column name of order, you're confusing the SQL parser, since order is a reserved word.
(a): Of course, this problem goes away if you stop using reserved words as column names but I assume you did that for a reason (such as a bucket-load of programs already depending on the fact that the column is called order).
Myself, I tend not to use generic names for columns (such as order or date), preferring instead things that don't conflict with the language (such as order_num or start_date). That way I don't have to worry about escaping.
You are using SQL reserved keyword order as a column name so use back-ticks to escape...like this
SELECT * FROM learningmaterial ORDER BY `order` ASC
I would suggest you to change the columnn name
Reference For List Of Reserved Keywords
ORDER is a reserved sql syntax keyword. you cannot use it directly
SELECT *FROM learningmaterial ORDER BY `order` ASC
-------------------------------^---------
in second case
SELECT *FROM learningmaterial ORDER BY order ASC
---------------------------------^-------^--
//this is a sql error
it doesn't make any sense.
Since Order is a reserved word, you need to wrap them using backticks not single quotes.
SELECT * FROM `learningmaterial` ORDER BY `order` ASC

IDs not sorting

I got an odd problem. Whenever I add a new entry to the database it gives it a higher id number, but somehow sees it as a lower number and puts it below the older ones.
And when sorting DESC in PHP I also get this order, does anybody know whats going wrong here?
I use $res = mysql_query("SELECT * FROM data ORDER BY 'id' DESC");to sort them, and it gives the same order as in the pic. (Not sure why i'm being downvoted here but ok..)
Pic:
Your query is:
SELECT * FROM data ORDER BY 'id' DESC
You are sorting by the string 'id', note the syntax highlighting when not within quotes. This means you get them in a random order. Remove the '. If you meant to escape the column id you should use back-ticks:
SELECT * FROM data ORDER BY `id` DESC
When you insert data on the tables, it does not mean that the new number (or the highest) always on the lowest row. It randomly inserts the record. The only way you can sort it when you retrieve the rows in by using ORDER BY clause, example
SELECT *
FROM tableName
ORDER BY ID DESC
So assume that ID is numeric. If you're ID is stored as string then you should convert it to numeric,
SELECT *
FROM tableName
ORDER BY CAST(ID AS SIGNED) DESC
UPDATE 1
It should be
$res = mysql_query("SELECT * FROM data ORDER BY `id` DESC");
not
$res = mysql_query("SELECT * FROM data ORDER BY 'id' DESC");
what you have done was you have surrounded the ID with single quote forcing the server to read it as String and not Numeric
When you are not using any ORDER BY clause, the order in PHPMyAdmin is kind of random. Indeed, new rows could take place of old ones.
I am curious how you sort DESC in PHP though.
Don't absolutely trust in GUI web interface because sometimes (not always) it bugs with session management, however you can run SQL Queries using it.
1- To run a SQL query, click on "SQL" on the navigation bar.
2- Enter your SQL in the box provided.
SELECT *
FROM tableName
ORDER BY ID DESC
3- Click "Go".

phpMyAdmin versus mysql_fetch_array - why can't I get GROUP BY to work?

I have a simple table called "board" that has a column called "sid" - that is just integers. Many of these are duplicates. I want to know only distinct values in this column, so I do this:
SELECT sid FROM board GROUP BY sid
When I run this query directly in phpMyAdmin, I get the set I was expecting. No problem. However, this bit of code returns every row in the entire table, without exception:
$sql = "SELECT sid FROM board GROUP BY sid";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo $row["sid"] . "<br />";
}
Does anyone know why? FYI I've tried every combination of DISTINCT and GROUP BY I could think of, but no matter what I do, I can't get a distinct set to echo out.
That sounds like very strange behavior, but why don't you try this:
select distinct sid from board
ACK. PEBKAC, sorry. Thanks for all the help. I didn't realize I had it nested in another loop and so the distinct resultset was actually echoing out multiple times.

mysql php query HAVING clause

Im trying to get this query to work but i get this error:
Unknown column 'zips.city' in 'having clause'
`$query = "SELECT
zips.*
FROM
zips
HAVING
zips.city LIKE '%$city%'
AND
zips.stateabbr LIKE '%$state%'
LIMIT 1";
$result = mysql_query($query) or die (mysql_error());`
my zips table has a city column, so im not sure what the problem is, i know im accessing the database because i can run this query with no errors:
$zip1query = "SELECT
zips.*
FROM
zips
WHERE
zips.zip = '$zip'
";
any advice would be much appreciated! thanks!
The having clause doesn't mean the same thing as the where clause : when running a simple query, you should use where -- which is what you did in your second query, that works.
having is used when the condition has to be applied on the result of a group by clause.
Which means that, here, your query should be build this way :
$query = "SELECT zips.*
FROM zips
where zips.city LIKE '%$city%'
AND zips.stateabbr LIKE '%$state%'
LIMIT 1";
With that, if you still have an error about a non-existing or not-found column (at least for city and/or stateabbr), it'll be because that column doesn't exist in your table.
In this case, there is not much we can do : you'll have to check the structure of your table, to determine which columns it contains.
You can check that structure using a web-based tool like phpMyAdmin, or using an SQL instruction such as :
desc zips;
For reference, quoting MySQL's manual page for select :
The SQL standard requires that HAVING
must reference only columns in the
GROUP BY clause or columns used in
aggregate functions. ...
Do not use HAVING for items that
should be in the WHERE clause.
For example, do not write the
following:
SELECT col_name FROM tbl_name HAVING col_name > 0;
Write this instead:
SELECT col_name FROM tbl_name WHERE col_name > 0;
...
The HAVING clause can refer to
aggregate functions, which the WHERE
clause cannot
Try using WHERE instead of HAVING.
The proper way to do it is by using a WHERE clause.
$query = "SELECT
zips.*
FROM
zips
WHERE
zips.city LIKE '%$city%'
AND
zips.stateabbr LIKE '%$state%'
LIMIT 1";
HAVING is to be used when you are GROUPing, see here for an explanation
o jeez sorry guys i figured out the problem, apparently i put a space before city when i named the columns in my table. so i renamed the column and it works thanks anyway chaps! but using the where function instead of having must speed things up alot, thanks guys!

Categories