Trouble with MySQL Query - WHERE AND / OR - php

This query generates a list of items per zip code.
$ziparrayimplode = implode(",", $ziparray);
$listingquery = "SELECT * FROM listings WHERE (CONCAT(title, description) LIKE '%".$searchstring."%') AND auc_cat LIKE '%".$category."%' AND zip IN ($ziparrayimplode) AND all_zip=$allzip ORDER BY list_ts DESC $pages->limit";
$listinghistory = mysql_query($listingquery) or die(mysql_error());
If I use "AND" in the WHERE statement for all_zip=$allzip then all the items that are true for all_zip will show, but not the items in $ziparray. If I use "OR" in the WHERE statement then the items true for $ziparray will be included as well as $allzip... but my search function won't work at all.
Am I phrasing this query correctly or should I use "OR" in the WHERE statement and look for the problem in the way the search is coded?

You could manage it playing with OR / AND operators precedence (your strange result seems to show that you're actually a "victim" of wrong usage of operator precedence), or just add parentheses.
...
AND (zip IN ($ziparrayimplode) OR all_zip=$allzip)
ORDER BY...

Related

php multiple AND Select Query

Hi There I'm trying to get some data with this SELECT statement and when I just select two items it gives me result but when I place third item it doesn't give any result.
$Query="SELECT * from tableName WHERE status='true' AND gid='".$gid."' AND section='".$cid."'";
Plz any solution.
this one works fine, but when I add third item status='true'. doesn't work.
$Query="SELECT * from tableName WHERE gid='".$gid."' AND section='".$cid."'";
First, let me say this: Double-quoted strings can parse your variables, so this line can work, too:
$Query="SELECT * from tableName WHERE gid='$gid' AND SECTION='$cid'";
Try to learn PHP basics about using single ' and double " quotes here: What is the difference between single-quoted and double-quoted strings in PHP?
Related to the database query, is status field is present in your database table? If not, it should NOT be included within the database, or it will return FALSE boolean value. Instead, use IF if you want to be 'selectively' filtering the status of the table.
if('your conditions here'){
$query = "SELECT * FROM tableName WHERE gid='$gid' AND section='$cid'";
}
I think your mistake is the status='true'
probable the database control its field with 1 or 0 value.

MySQL / PHP: Fetch multiple values from 1 column in Database

I'm trying to select multiple values from 1 column in my MySQL database. I have a Table 'products' with a column 'category'. Categories: Home, Garden, Cars, Bicycle etc. I want to fetch the number of products with these categories for statistics. It sounds simple but I can only get it done with allot of code. I want all of these categories to be variables so I only have to put my variables in my statistics engine to do the calculation. Right now this is my code to fetch the number of products with category 'Garden':
$query = "SELECT * FROM products WHERE category='Garden'";
$result= mysql_query($query);
$row = mysql_fetch_array($result);
echo "$row[category]";
Repeating this for every category does 't seem right to me.. Does anyone understand my question and have a solution?
I think this is what you want
$query = "SELECT `category`, COUNT(`category`) FROM `products` GROUP BY `category`;";
try this
$query = "SELECT *, count(*) as counts FROM products group by category";
$result= mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo $row['category']." ". $row['counts'];
}
you have to use while to fetch multiple categories.
you need to group by category to get distinct categories.
Just use a while as a loop to get the data.
What is While Loop?
The do while construct consists of a process symbol and a condition. First, the code within the block is executed, and then the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false. Because do while loops check the condition after the block is executed, the control structure is often also known as a post-test loop. Contrast with the while loop, which tests the condition before the code within the block is executed.The do-while loop is an exit-condition loop. This means that the code must always be executed first and then the expression or test condition is evaluated. If it is true, the code executes the body of the loop again. This process is repeated as long as the expression evaluates to true. If the expression is false, the loop terminates and control transfers to the statement following the do-while loop.
Just use the code below to fetch multiple values.
$query = "SELECT * FROM products WHERE category='Garden'";
$result= mysql_query($query);
while($row=mysql_fetch_array($result))
{
echo "$row[category]<br>";
}

PHP MySQL statment with AND and OR

I have a PHP MySQL statement and basically what I want is to check for that table element matches and then check a second table element matches or a third table element matches, sort of like this
if ref=ref (AND page=page OR allpages=1)
that means search for all pages with ref=ref and then in that recordset check if page=page or if all pages=1
so MySQL statement is this:
$sql=mysql_query("SELECT * FROM content WHERE ref='$ref' AND page_ref='$page_ref' OR allPages='1');
But it is taking records from the db that don’t match the ref but allpages=1
Is there some way of bracketing this or restructuring the statement?
Your if ref=ref (AND page=page OR allpages=1) was nearly right, but you want the AND out of the brackets:
if ref=ref AND (page=page OR allpages=1)
Implemented:
$sql=mysql_query("SELECT * FROM content WHERE ref='$ref' AND (page_ref='$page_ref' OR allPages='1')");
Note: you were missing a closing " from the query as well (though I suspect this was a copy error when creating the question)
Further improvement (concatenation and backticks):
$sql=mysql_query("SELECT * FROM `content` WHERE `ref`='".$ref."' AND (`page_ref`='".$page_ref."' OR `allPages`=1)");
Simply add brackets like this:
SELECT * FROM content
WHERE ref='ref'
AND (page_ref='page_ref' OR allPages='1')
-------^------------------------------------^----Add here
So your whole query should be:
$sql=mysql_query("SELECT * FROM content WHERE ref='$ref' AND (page_ref='$page_ref' OR allPages='1')");
User Operator Precedance.
The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18.
"SELECT * FROM content WHERE ref='".$ref."' AND (page_ref='".$page_ref."' OR allPages=1")
I think
SELECT * FROM content WHERE ref='$ref' AND (page_ref='$page_ref' OR allPages='1')
it is a priority matter. You can read about operators precedence in the corresponding manual page.
Also, remember, that mysql_* functions are officially deprecated, so use mysqli_ or PDO instead.
You can add brackets to your mySQL statement in just the same way as you add them to a PHP statement. Just make sure your expression is bracketed in the same way as your desired logic.
$sql=mysql_query("SELECT * FROM content WHERE ref='$ref' AND (page_ref='$page_ref' OR allPages='1')");
You should set braces around the OR comparison:
WHERE ref='$ref' AND ( page_ref='$page_ref' OR allPages='1' )

Dynamic PDO Query - With AND / OR

I have two issues, the first as the title states is that I need to have dynamic query with AND/OR in it. I fully understand the AND part (I've done a bunch of these) however, the OR part is very confusing to me because looking at this following sql :
$sql = SELECT * FROM table WHERE 1
then if you add an OR statement if a condition is met :
if(isset($_POST['OR'])){
$sql. = " OR peaches = :good";
}
then the query will return WHERE 1 OR peaches = :good
Again I understand the part with the AND, but I do not understand how to set up the OR part.
This is how I have set up the AND / OR selection (and this works)
The second issue I am facing is this code snippet from the same script (please read code comments) :
$sql .= " GROUP BY anum"; // I always group BY anum no matter what
if ($count !== "") { // if COUNT is not ""
$sql .= " HAVING COUNT(session.anum) :count"; // Then I want the user to be able to choose the operator (> < => =< =) and the dynamic number for it to use
$placeholder[':count'] = $count; // Then add the key :count to an array with the value of $count
}
$dynamic = $this->db->conn_id->prepare($sql);
$dynamic->execute($placeholder);
So as you notice I give the named parameter (:count) the value of $count, however this does "not work".
Is it possible to do what I am trying to do ($sql .= " HAVING COUNT(session.anum) :count";)
If not then I could just do : $sql .= " HAVING COUNT(session.anum) $count";
but that would defeat the purpose of PDO.
Any help would be great
Problem 1:
The reason that some developers use WHERE 1 when they have optional search terms is that an expression like TRUE AND <condition> is always equal to <condition>. This is basic boolean algebra.
But this is not the case for OR expressions. TRUE OR <condition> is always simply TRUE. You could modify your base query to use WHERE 0 so that when you append an OR term it comes out as WHERE 0 OR <condition>. Any expression like FALSE OR <condition> is always equal to the <condition>.
If you need to support both AND and OR in the same SQL query, you need to start putting parentheses around terms so they evaluate in the way you intend. I'm not going to explain boolean algebra and MySQL's operator precedence in this StackOverflow answer. But suffice to say that simply appending terms with .= isn't going to work when you have a mix of AND and OR terms.
Problem 2:
Parameters are very useful, but they don't solve every case of dynamic SQL. You can use an SQL parameter in place of a single literal value, but nothing else.
Not table names
Not column names
Not lists of values (like an IN( ) predicate)
Not SQL keywords
Not expressions
Not operators
You have to use string interpolation to include a user-chosen operator in your HAVING clause.
It's recommended to use whitelisting to avoid risk of SQL injection when you need to interpolate dynamic content and can't use a parameter.
For the first issue, what is the problem exactly?
For the second, MySQL manual says that you can't use functions on having clauses.
You can do like this:
SELECT *, COUNT(session.anum) AS total GROUP BY session.anum HAVING total > :count

SQL Operators: AND and OR

I'm just wondering if you can use both of them in a PHP code. I thought something like this:
$sql2 = mysql_query("SELECT * FROM forum WHERE id='$topicsnumber' AND main='0' OR main='1' OR main='2'");
while($row=mysql_fetch_array($sql2)) {code in here}
So that it checks it like this WHERE id='$topicsnumber' AND (main='0' OR main='1' OR main='2').
Is this possible?
Yes, it's possible with parentheses around the conditions, but it's better written as
mysql_query("SELECT * FROM forum WHERE id='$topicsnumber' AND main IN ('0','1','2')");
That way you don't have to worry about operator precedence.
If main is a numeric data type, you can drop the apostrophes around the numbers in your query.

Categories