Mysql query built my phpmyadmin doesn't work in PHP with WHERE clauses
Just trying to select all rows with no comments, or comments < 5 characters.
Starting from basics, this works:
$query= "SELECT * FROM `comments`";
$result = mysql_query($query);
What doesn't work is:
$query = "SELECT * FROM `comments` WHERE `comment` = ''";
or
$sql = "SELECT * from comments WHERE LENGTH(comment) < 5 LIMIT 30";
I've put limit 5 because when I do a COUNT on the "empty" comments, it says there's 4 bytes there. The column is not NULL (don't blame me, I didn't write it!)
I've even tried using phpmyadmin to change the "empty" values to the word "chicken", then running
So, I used phpmyadmin to change all the instances of comments < 4 characters to the word "chicken".
$query = "SELECT * FROM `comments` WHERE `comment` = 'chicken'";
As with ALL of the above errors, it spews out:
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
But if I do
$emptycomment = "chicken";
$query = sprintf("SELECT * FROM `comments` WHERE `comment` = $emptycomment");
Invalid query: Unknown column 'chicken' in 'where clause'
WTF?! But that works perfectly in phpmyadmin! (all above tested on stable and alpha versions)
I also saw where someone else put:
$query = sprintf("SELECT * FROM `comments` WHERE `comment` = 'chicken'");
Again, no dice on any of the above.
The stupid thing is, these all work perfectly directly as a mysql query, and the above were even generated by phpmyadmin! I've even updated php to 5.3.2, the mysql installed is 5.1.52
I've tried making it EXACTLY as per example 2 here, using开发者_开发知识库 variables for everything. http://php.net/manual/en/function.mysql-query.php
I've followed the tutorial here: http://www.devshed.com/c/a/MySQL/Null-and-Empty-Strings/3/
I've browsed about 20 articles here at Stackoverflow.
It's 11:15am. I started at 6:30. Getting a bit frustrated here. Thanks!
$emptycomment = "chicken"; $query = sprintf("SELECT * FROM comments WHERE comment = $emptycomment");
Have you tried to print $query after? You missed quotes around string variable
$query = "SELECT * FROM comments WHERE comment = '" . mysql_real_escape_string($comment) . "'";
I ran into a similar problem where an "empty" field wasn't NULL. What happens if you try the chicken with:
$query = "SELECT * FROM comments WHERE comment LIKE '%chicken%'";
This will give you a match even if you have CR/LF and other strange "invisible" characters involved.
From my experience the query generated by phpmyadmin puts quotes where I believe there shouldn't be any such as table names and once I remove those it works. I. E. "SELECT * FROM 'db'.'table'" doesn't work but "SELECT * FROM table" does.
精彩评论