Use Three Conditions In WHERE Clause Of Mysql Query?

May 30, 2011

Here is my current MySQL syntax (but this doesn't work):

SELECT * FROM posts WHERE userID = $userID AND postBy = $postBy AND postType = 'unread'

Here is the picture of my MySQL table (a picture can show more than words!) I want to know if there is any other way of doing it or if I have to forget this idea?


Multiple Conditions In Where Clause

Jul 27, 2008

I need multiple conditions in the where clause, I did this and it is not working.

 $result5 = mysql_query("SELECT * FROM test WHERE (date BETWEEN '$sqlfrom' AND '$sqltoprevious') AND room_id = '$room_id' AND hotel_id = '$hotel_id'") or die (mysql_error());
while ($row5=mysql_fetch_array ($result5))
$dates = date('d M Y', strtotime($row5['date']));
$rate = $row5['rate'];

So, what I want is the dates and rates from the table test where the dates are between $sqlfrom and $sqltoprevious and where the room id is $room_id and hotel id is $hotel_id.

View 2 Replies View Related

Mysql Query Multiple Conditions.

Jan 31, 2007

Hi i want to do a mysql select with more than 1 conditions.

I have this:

select * from phpbb_posts where post_time = 1064078039;

but i want to be able to select multiple post_time's. I'm guessing it was something like this:

select * from phpbb_posts where post_time = (1064078039, 1034078039, 10640744039, 10643378039, 1064076039);

but thats obviously wrong. Anyone can help here?

View 1 Replies View Related

MySQL Query With Multiple WHERE Conditions

Jun 9, 2010

however I've not seen any result that would come close to my case. I have a query with 3(THREE) WHERE conditions to be met as follows:

$sql = mysql_query("SELECT type_name, COUNT(type_name) FROM tb_tracker WHERE session_id = '".$id."' AND type_name = 'deposit'AND expiry > '".$time."' GROUP BY type_name");

I know the query above is flawed because the second AND will not get executed however I'd like to use all of the conditions above OR didn't do the trick for me

View 2 Replies View Related

Simple MYSQL Query - 2 WHERE Conditions Syntax

Apr 27, 2006

I am trying to formulate a mysql select statement where it selects all the fields below I am having trouble however with WHERE indMatch.player2ID = '$username' I want to add to this WHERE indMatch.p2ConfirmResult is equal to 0 aswell but I do not know the syntax. Code:

View 4 Replies View Related

Switch MySQL Query Conditions, After All Results Listed?

Dec 28, 2010

Let's assume I have a table with the fields "fruit" and "color". What I am looking for is a loop where in the first round all fruits with red color will be selected and in the second round all as green fruits.

//first round
$fruit_color = "red"
//second round
$fruit_color = "green"

View 4 Replies View Related

Write A MySQL Query With A Variable In The WHERE Clause?

Nov 17, 2010

how to write a MySQL query with a PHP variable in the WHERE clause. I've tried {} {'xx'} and () and it still doesn't work.

Here is the code

include ("include/connect.php");
include ("include/session.php");


So I'm trying to show the email address for a record that matches the username of the user logged in.

View 5 Replies View Related

MySQL Query - INSERT - Unknown Column 'test' In 'where Clause'

Nov 28, 2007

I have a registration script on my website, and it was working fine, I added a second MySQL INSERT query to it, for another table so I can use JOIN's later on with the second table, but I keep getting the same error:

Unknown column 'test' in 'where clause' can someone see whats wrong with this? Code:

View 6 Replies View Related

Mysql If Conditions? Loops Conditions?

Aug 10, 2005

Are if statements and looping possible in a sql command line?

Well, actually I want to Select only 2 unique "ids" from a table to be shown per page....but this seems impossible to do using mysql. But I want to verify.

If the ids are listed like this:


Can I use a mysql query to only show 1 and 2 on one page, 3 and 4 on another page, 5 and 6 on another page, and so on?

View 1 Replies View Related

Mysql OR Clause Respective To AND Clause?

Jul 1, 2011

I have a form for filtering/sorting database records.

I'm filtering posts by author, category, and tags. I'm using AND clause for author and category and OR clause for tags (multiple tags can be entered)

A query looks like this

FROM (`posts`)
WHERE `author` = 'dan'[code]....

The query above returns posts that contain any tag searched regardless of the author or category.I want to return posts containing tags ebook, ipad, apple only within the author name dan and category technology.

View 2 Replies View Related

UPDATE Clause In MYSQL Update Multiple Records In One Query?

Nov 12, 2008

well i have this messages table with sample values like these:

msg_id recipient_id read locked new
0 1 N Y Y
2 1 Y N N

ok, so lets just say this is a messaging table, and i want to reset all messages addressed to recipient with id=1 i was wondering why UPDATE `messages` SET `new`='Y',`read`='N',`locked`='N' where `recipient_id`=1;

doesn't work, MYSQL always returns 0 affected rows.. to robert gamble: yes, im sure the values were changed, since my purpose for this update query is to reset the data i was using for the testing phases :D

View 3 Replies View Related

REGEX: Can't Seem To Replace LIMIT Clause In Query Using Preg_replace ($pattern, $replacement, $query)

Apr 13, 2006

Want to replace the limit clause in a query, but can't get it right.
What's wrong with this:

$pattern = "(.*)limit (.*)";
$replacement = '$1'
$replacement .= "LIMIT $limit";
$replacement .= '$2'
$query = preg_replace ($pattern, $replacement, $query);

View 1 Replies View Related

MySQL Ignores Indexes If Query Contains Conditions "greater Than" Or "smaller Than"?

Aug 28, 2010

why MySQL is not using indexes in queries with conditions "greater than" or "is not empty":

PHP Code:

select from table where col1='$col1' and col2 !='';

PHP Code:

select from table where col1='$col1' and col2 > '0';

Indexes are used only if query contains condition "equal to":

PHP Code:

select from table where col1='$col1' and col2 ='$col2';

Don't know how can I use indexes if I need to select columns where value is greater than something or value is not empty

View 2 Replies View Related

Search Form Returning Error "Invalid Query: Column 'name' In Where Clause Is Ambiguous SQL Query"

Apr 25, 2009

This is my code and the error is underneath.

$search = $_POST["search"];
$db = "`char`";
$connection = mysql_connect("localhost","wowbasec","PASSWORD REMOVED");
mysql_select_db("wowbasec_class", $connection);
$query = "select * from characters, location WHERE name='$search'";

Invalid query: Column 'name' in where clause is ambiguous SQL Query: select * from characters, location WHERE name='Harry'

View 8 Replies View Related

Trying To Put A Sub - Clause Into A Query

Aug 16, 2010

I have 2 tables "properties" and "images" the images table contains all the images for each property, linked via a 'prop_id' at the moment I'm selecting all the properties and just 1 image for each property using this query :

$sql = "SELECT DISTINCT(t1.prop_id) AS pid, t2.image_thumb,t1.prop_name,t3.loc_type_name   
FROM properties AS t1  
LEFT JOIN images AS t2 ON t2.prop_id=t1.prop_id
LEFT JOIN location_types AS t3 ON t3.loc_type_id=t1.loc_type_id
WHERE t1.prop_online='1'
GROUP BY pid    
ORDER BY t1.prop_name ASC";

this works fine but my problem is that the images are ordered using a field called "image_order" and I'd like the first image in the order (with an "image_order" value of 1) to be selected by this query but what's happening is that the query above is selecting the image with the lowest "image_id" (the first image uploaded) and NOT the first image in the ordering So ... what I'd like to do is to include a bit in the query that says "select the lowest image_order value" kind of like this pseudo-code :


View 1 Replies View Related

Speed Up Query With No WHERE Clause?

Jul 14, 2010

I have about 1 million rows so its going pretty slow. Here's the query:

$sql = "SELECT `plays`,`year`,`month` FROM `game`";

I've looked up indexes but it only makes sense to me when there's a 'where' clause.

View 5 Replies View Related

Fetch Rows From Wpr_subscribers Provided That The Conditions In The Query?

Jun 25, 2011

I have the following query to fetch rows from wpr_subscribers provided that the conditions in the query.

SELECT subscribers.* FROM wpr_subscribers subscribers, wpr_followup_subscriptions subscriptions WHERE AND AND
subscribers.confirmed=1 AND
subscriptions.type='autoresponder' AND
subscriptions.eid=$autoresponder_id AND
subscriptions.sequence = -2 OR
CEIL((subscriptions.last_date-subscriptions.doc)/86400) >= $message_index

The query returns two of every row. How do I solve this issue?

View 2 Replies View Related

Pull Data From A Second Sql Query Using A Where Clause

Apr 12, 2006

I am trying to pull data from a second sql query using a where clause = two fields from the first query. I am trying to gather from the second query, any data where we have a match from either of the two in the where clause.

sql=my select 1,2 from t1

while $row {


sql=select 1,2 from t2 WHERE 1 = '$one' or 2 = '$two' group by 1,2

while $row2 {

//trying to output all rows that either 1 or 2 from t2 match 1 or 2 from t1. so all grouped results from 1 display all unique results in 2all grouped results from 2 dispaly all unique results in 1 where either 1 from t1 = 1 from t2 or 2 from t1= 2 from t2.

View 5 Replies View Related

Conditionally Add A Clause To Query In Script?

Sep 29, 2010

In my search form I have, value male, value female, and value both. If you select both, I do not wish to have at WHERE the "sex = '$sex'" Should i do it like this:

if(empty($sex)){ // value empty if you chose "both"
$query = "SELECT firstname, lastname, id, user_name, sex, last_access, bostadsort FROM users WHERE (firstname LIKE '%$firstname%' OR lastname LIKE '%$lastname%')";
$query = "SELECT firstname, lastname, id, user_name, sex, last_access, bostadsort FROM users WHERE (firstname LIKE '%$firstname%' OR lastname LIKE '%$lastname%') AND sex = '$sex'";

View 3 Replies View Related

Doctrine Sql Query, Where Clause Not Taken Into Account?

Jul 1, 2011

I suppose my problem is simple but i can't get it fixed...Here is my query:

$this->invites = Doctrine_Query::create()
->from('Utilisateur u')

View 1 Replies View Related

Doctrine - Clause Included Only When Necessary In A Query?

Nov 7, 2010

I want to use a single query to retrieve: items of any categories (no filter applied); only items of a single category (limited to a particular category); For that purpose I should be able to write a Doctrine query which would include a where clause only when certain condition is met (eg. part of URL existing), otherwise, where clause is not included in the query. Of course, i tried with using the If statement, but since doctrine query is chained, the error is thrown.

So i guess the solution might be some (to me unknown) way of writing doctrine queries in an unchained form (by not having each row started with "->" and also having each row of a query ending with semicolon ";")

That way the usage of IF statement would be possible i guess. Or, maybe there's already some extremely simple solution to this matter?

View 2 Replies View Related

Making A SQL Query With An Array In WHERE Clause

Mar 14, 2011

i have a problem making a SQL Query with an array in my WHERE clause.

For example:
My Array:
$myarray[1] = "hi";
$myarray[2] = "there";
$myarray[3] = "everybody";
My MySQL Statement:


But if i had thousands of entries in my array, the SQL Statement would be too big and slow, right?

View 4 Replies View Related

Use Prepared Statement In Query With 'IN(.....)' Clause?

May 20, 2011

Is there a (tricky/non-standard) way to do this?Would something like

$stmt = $db->prepare( 'SELECT title FROM episode WHERE id IN (?, ?, ?, ?);

work? So if I wanted to search for a variable amount of ids, could I do

$ids = array(1,2,3,4,5,6,7);
$idSection = implode(array_pad(array(), count($ids), '?')) //To give ?,?,?,?,?,?,?
$stmt = $db->prepare( 'SEL

View 1 Replies View Related

Query Based On 2 Conditions - Select If The Doc_type Is Either S OR F But This Doesn't Work

Oct 23, 2009

I want to select if the doc_type is either s OR f but this doesn't work:

Code: [Select]$query2 = "SELECT * FROM members WHERE doc_type='s' && doc_type= 'f' ORDER BY username";

Also If I want to do two sorts can I do this: Code: [Select]$query2 = "SELECT * FROM members WHERE doc_type='s' && doc_type= 'f' ORDER BY doc_type, username";

View 4 Replies View Related

Select Query With WHERE Clause Doesn't Work Any Longer

Feb 1, 2005

I have a table in MYSQL that I'm trying to set up a search query on (so it can be searched for records by an author's name). I did it several weeks ago and then it worked, but now when I try to run the search it returns no records although I know they are there. To my knowledge nothing has changed in my PHP script. I checked everyhting repeatedly but must be blind to the error. It's driving my crazy since I know it worked fine at one time.

If anyone has the energy to take a look and offer their suggestions, it would be greatly appreciated. Here is my script. PS. I can add a record and view all the records through other scripts with no problem.

<?php # Script 11.6 - md_seaauthor.php
// This page searches titles by author.

// Set the page title and include the HTML header.
$page_title = 'Search Mother Daughter Bookclub by Author'
include_once ('header4.html');

require_once ('Connections/mysql_connect.php');
// Connect to the database.

$query = "SELECT * FROM mdbookclub WHERE author ='$author'";
$result = mysql_query ($query);
while ($row = mysql_fetch_array($result)) {
$md = $row['md_id'];
$title = stripslashes($row['title']);
$author = stripslashes($row['author']);
$f_author = stripslashes($row['f_author']);
$pub_year = stripslashes($row['pub_year']);
$call_number = ($row['call_number']);
$display_block .= "<p><strong>Author:</strong> $author <strong>Title:</strong> $title<br />
<strong>Publication year:</strong> $pub_year <br />
<strong>Call number:</strong> $call_number </p>";

View 1 Replies View Related

My Code POSTS The ID From Each Menu Then Puts That ID Into The WHERE Clause Of An SQL Query.

Apr 18, 2007

I've got two drop down menus that I'm using to filter some data. It works when the user selects an option from both menus but always return ZERO records when only one of out the two menus have been set. My code POSTS the ID from each menu then puts that ID into the WHERE clause of an SQL query. Code:

View 2 Replies View Related

Creating Subtotals And Grand Totals For Group By Clause In Sql Query

Mar 24, 2010

I tried looking for several reporting tools for PHP however I was not happy with what i found and figured that straight PHP combined with some basic css will allow me to make all the reports i need, without having to work around the reporting frameworks own quirks and limitations.

I need to create very simple reports like this:

Group 1
Record 1
Record 2
Group 1 Total


Does anyone have any recommendations on how to do this. Using the Group By clause in mysql will give me the group totals but not list the individual records within the groups or give me the Report Total.

Is there a straightforward way to do this or should I write php code to loop through my records and sort them and then create the necessary totals and subtotals?

View 2 Replies View Related

Doctrine: Remove Part Of A Where Clause From Select Query Inside Listener (preDqlSelect)?

Oct 14, 2009

My listener is part of a behavior, that should remove all is_published checks in the where clause of any called select query. Adding a part to a clause is really easy, but how to remove one. There are some functions like Doctrine_Query->removeDqlQueryPart('where'), but that removes the complete where clause, while I only need the 'is_published = ?' part to be removed.

However I could handle this manually somehow, with regex or something. But the tricky part is, how to remove the parameter represented by the '?' from the corresponding parameters array (retrievable by Doctrine_Query->getRawParams()). So I ask, is there a clean way to transform this kind of query: ...FROM Video v WHERE v.is_published = ? AND v.start_date < ? AND v.end_date > ? to this stripped one and without messing up the params represented by the question marks: ...FROM Video v WHERE v.start_date < ? AND v.end_date > ?

This is of course just a simple example, my queries are a bit more complex. Unfortunately I'm stuck with doctrine 1.0.x because of the symfony framework.

View 1 Replies View Related

Use Zend_DB - If I Pass Query With A Join Clause Page Just Hangs And Not Error Is Return?

Apr 21, 2010

I am trying to understand how to use Zend_DB in my program but I have some problem. The class below (DatabaseService) work when I pass it a simple query. However, if I pass it it query with a join clause my page just hangs and not error is return. I cut and paste the qry in a query browesr and it is valid

$SQL = "select name from mytable"
$db = new DatabaseService($dbinfo)
$db ->fetchall($SQL ) // works[code]....

View 1 Replies View Related

Doctrine And Aliases From The Select Clause In The Where Clause?

Jun 30, 2010

I am using an alias in my select clause ("AVG(u.rating) as avg_rating") and would then like to add this in my where clause "avg_rating > 3" but when I try and run this query I get a "Unknown column 'u3__1' in 'where clause'." Does anyone happen to know how I can get my where clause to see the alias? This alias works in the orderBy with no issue, just not the where.The above was an example, but here is the real rendered SQL, not as simple. My issue is actually with an alias on value with a bunch of conditionals. And the alias I am having trouble with is the generated date which has recurrences and doesn't have to every date field populated. So I am posting a simple SQL query that gives me the same issue.

SELECT t.type_id as type_alias, t.* FROM theme as t WHERE > 1 AND type_alias = 3

View 1 Replies View Related

Mysql IN Clause With Php

May 7, 2007

im having some trouble with this bit of code. im sure its an easy fix but i cnt seem to put my finger on it.

$catline = "222,223,224,225,";
WHERE cat IN ('".substr(str_replace(",","','", $catline),0,-3)."').

View 2 Replies View Related

Checking For Values In MySQL And Other Conditions Not Working?

Jul 16, 2005

I'm trying to redirect when testing for certain condidtions as shown
below. When the conditions are ture, it redirects, but still goes ahead and
processes the sql query. What am I doing wrong??? And then sometimes when
the conditions are correct, it doens't redirect. It appears to be very

//Check for repeat name
$result = mysql_query("SELECT * FROM survey WHERE FirstName =
'".$FirstName."' AND LastName = '".$LastName."' ");
$num_rows = mysql_num_rows($result);
if($num_rows > 0){header("location: ./oops.htm");};

//Check for repeat email
$result = mysql_query("SELECT * FROM survey WHERE EmailAddress =
'".$EmailAddress."' ");
$num_rows = mysql_num_rows($result);
if($num_rows > 0){header("location: ./oops.htm");};

//Check for existance of first name, last name, and email
if(!$FirstName){header("location: ./oops.htm");};
if(!$LastName){header("location: ./oops.htm");};
if(!$EmailAddress){header("location: ./oops.htm");};

$newrecord = ("INSERT INTO survey (FirstName) values ($'Joe')");

View 2 Replies View Related

Where Clause Not Working In MySQL

Dec 23, 2006

I am trying to do a search on a table and allow input from the user to construct a where clause. When I tried to search for a list of organizations with "P" in the name using the following: Code:

View 1 Replies View Related

About Using Count() In MySQL WHERE Clause?

Jan 24, 2009

Alright, I have a mysql table like the following.tbl_players


View 16 Replies View Related

MySQL: Using Bit Function (Bitwise AND) In In The WHERE Clause

Aug 13, 2005

I want to add GEO target feature to my in-house ad system. The first idea is add N columns to represent N countries: Code:

View 1 Replies View Related

Mysql LIMIT Clause For Arrays

May 22, 2005

I am trying to implement pagination for my news script ran on flat text files, and i can't get the 'core' idea to work - to display particular items from an array (For example display all items from 10 to 20, from 0 to 10, from 1000 to 2000 - you get the idea).

This is where i got one more mysql advantage - you can use a very handy LIMIT clause there. So how do i "emulate" it with arrays? It's got to be very simple, but i suck at programming. I tried array_slice($array, 10, 10) ; array_slice($array, 10, 20) and same for array_splice. Code:

View 1 Replies View Related

MySQL - Select 6 Rows - Each With A Different 'WHERE' Clause

Jun 18, 2011

I'm pretty good with MySQL, but this is something I have never done. What I want to do is make an SQL code to select 6 rows, each with their own WHERE clause. What I am trying to do is get 6 rows, and each will be the most recent "video" that was posted. there are 6 categories, so that's why I have 6 rows. I want it to pull the most recent by it 'id' number. I'd do it with 6 different SQL queries, but I assume that would be slower (unless this is the only way to do this?) From that small snippet, I would like to end up with is this:

2 --> 21
6 --> 16
8 --> 14 (Picks 14 since it's largest.)

Final Working Code

$sql="SELECT video_category, MAX(video_id) AS video_id FROM videos GROUP BY video_category";
while($rows=mysql_fetch_array($result)) {
echo $rows['video_category'] . " --> " . $rows['video_id'] . "<br>";

View 4 Replies View Related

Negative Values In MySQL IN Clause?

Mar 2, 2011

I have a view like this:


View 2 Replies View Related

MYSQL, Check Empty Table In Where Clause?

Nov 24, 2006

The following where clause (expurgated) suits my needs right up until the table emailman is empty (which it frequently is) and then it returns an empty set (which is bad;-) This is actually an "AND emailman.statment, but didn't I think the rest was really relevant.

Code: .....

View 3 Replies View Related

Use A WHERE MySQL Clause In A Statement Which Can Fetch All The Records?

Jul 10, 2011

How can I I am settings the WHERE condition conditionally. Like...

if (this) {
} elseif (that {
'SELECT * FROM table WHERE category='.$mycondition

What should be the value of ???? so that when I pass it to the sql statement it fetches me all the records. I was thinking that WHERE category='*' might work but it does not.

View 3 Replies View Related

Imploded Integer Array For Mysql NOT IN Clause?

Jun 15, 2011

I've been trying to use a PHP integer array for a MySQL query that uses the NOT IN clause, but despite no errors it seems to always return the results I want filtered out.


$IDS = $_SESSION['Posts'];
$Select = 'SELECT *
FROM status
WHERE (W_ID = '.$ID.')
AND (ID NOT IN ("'.implode(',', $IDS).'"))


I've made sure that $IDS is treated as an array. Also I have tested to see whether there are values stored within the array. I have also not quoted the integer array, but then I got a mysql syntax error for not having them.

View 3 Replies View Related

Order By MYSQL Dynamic Clause. Using $_REQUEST?

Nov 3, 2010

I have a $_REQUEST variable jump menu on my page allowing people to change the ASC or DESC order by post_time.The problem is getting the default to DESC order and having it work without changing the URL $_REQUEST variable.Here is what I have:

jump menu:
<form name="form" id="form">
<select name="jumpMenu" id="jumpMenu" onchange="MM_jumpMenu('parent',this,0)">
<option value ="?post_time=DESC"

View 3 Replies View Related

Codeigniter - Escaping Values When Passing Array To Query With "in" In The Where Clause?

Jun 2, 2011

I have the function below in my model for a codeigniter project, and the variable $id is an array and for example, contains (1,2,3). Now that i'm revisiting it, I think that i'm not actually escaping my array $id. I think I would have to change the line
$id = $this->db->escape($id)

If I do that, then it puts single quotes around every element in the array and treats it as one long string like this: '(1,2,3)'. I am not actually escaping my variable and either suggest a solution or let me know if this is a bug within the codeigniter framework?

function get_ratings($id)
$this->db->escape($id); // had to manually escape the variable since it's being used in an "in" in the where clause. [code].....

View 3 Replies View Related

Query Using "IN" WHERE Clause With Zend_Db_Adapter_Mysqli::fetchAll()?

Jan 7, 2011

I'm having a strange problem with Zend_Db_Adapter_Mysqli. I need to query multiple items by ID from my database, so I have the following SQL,

SELECT * FROM mytable WHERE id IN (1,2,3)

This query works fine. I then try and do this programatically with Zend_Db_Adapter_Mysqli,

$sql = 'SELECT * FROM mytable WHERE id IN (?)';
$ids = array(1,2,3);
$result = $adapter->fetchAll($sql, implode(',', $ids));

The problem is for the above PHP I only get back 1 result instead of the expected 3. I've tried just passing the $ids instead of using implode(), but I just get an error. What am I doing wrong?

View 4 Replies View Related

Nest One Mysql Query Within Another (for Cross Referencing Another Table In The Middle Of That First Query)?

Jun 15, 2001

How do i nest one mysql query within another (for cross referencing another table in the middle of that first query)? for example:

i am referencing a table with news posted by members and in the middle of that reference i want to reference an up to date version of their email address as listed in their profile (in case they change it after posting a news message).

View 2 Replies View Related