SQL query issues: [1] Count(*) and [2] using NOT vs <> - php

I have been staring at this code so long it is starting to bleed together. So let's get a couple things out of the way:
I am a low-moderate level SQL user and am still learning the best ways to accomplish queries and such
I have been building a PHP based quote-generator tool that ties in with an SQL database
Now, here is what I am trying to accomplish:
I would like to have pagination with the results of quotes that have been created with a status that is NOT "Dead", "Duplicate", or "Signed" and the ID does NOT equal 999 (because I wanted the quotes to jump to 1000 and I did not build the database correctly at first)
Here is what I have accomplished:
I was able to create the basic structure and it works just fine on page 1... then it all goes sideways. I was thinking that it was something to do with my count(*) query, but that seems fine - well functional, at least:
$countQry = "SELECT COUNT(*)
from needsassessment
WHERE ID <> 999
AND status <> 'Dead'
AND status <> 'Duplicate'
AND status <> 'Signed'";
$countResult = $mysqli->query($countQry);
while($rowQ = mysqli_fetch_array($countResult)) {
$totalRows = $rowQ[0];
$each = ceil($totalRows/$limit);
$where = "WHERE ID > 0";
if ($totalRows == 0) {
echo "You have not created any quotes.";
}
}
$limit = 15;
if (isset($_GET['q']) && $_GET['q'] !== "") {
$offset = $_GET['q'];
} else {
$offset = 0;
}
$query = "SELECT * FROM needsassessment $where
where $and
AND ID <> 999
AND NOT status = 'Dead'
AND NOT status = 'Duplicate'
AND NOT status = 'Signed'
ORDER BY ID DESC LIMIT $offset, $limit";
$result = $mysqli->query($query);
$row_cnt = mysqli_num_rows($result);
if ($row_cnt == 0) {
echo "You have not created any quotes."; die;
}
if (!isset($each)) {
$each = $row_cnt/$limit;
}
if ($each > 1) {
echo "<ul class='pagination'>";
for($i=1,$y=0;$i<=$each,$y<=($each-1);$i++,$y++) {
echo "<li><a";
if ($offset == ($y*15)) {echo ' class="active"';}
echo " href='?q=".($y*15)."'>$i</a></li>";
}
echo "</ul>";
}
Okay, so here are my questions:
I saw someone say that using PHP's mysqli_num_rows() is wrong and
that I should use SQL's COUNT(*). Why? Does it have a different result or take longer?
What is going on with page's
2 and 3? When I do a row count it says it sees 15 rows but only some
are showing. I have some records (i.e. those with a status of
"Signed" or "Dead") that are excluded from this list and I was
thinking that may have been the issue, but it doesn't seem to matter
on the first page.
What is the difference - if there is one -
between "NOT" and "<>" for checking records?
If you have any suggestions or if I have done anything blatantly wrong or inefficiently please let me know so I can correct it :)
Thanks to all that make Stack Overflow AWESOME!
EDIT:
There certainly was some code missing:
if (!isset($sst)) {
$where = "";
$sst = "";
$countQry = "SELECT COUNT(*) from needsassessment WHERE ID <> 999 AND status <> 'Dead' AND status <> 'Duplicate' AND status <> 'Signed'";
$countResult = $mysqli->query($countQry);
while($rowQ = mysqli_fetch_array($countResult)) {
$totalRows = $rowQ[0];
$each = ceil($totalRows/$limit);
$where = "WHERE ID > 0";
if ($totalRows == 0) {echo "You have not created any quotes.";}
}
}
else {
if ($option !== "*") {
$where = "WHERE ".$option." LIKE '%".$sst."%'";
}
if ($option == "*") {
$where = "WHERE status LIKE '%".$sst."%' OR title LIKE '%".$sst."%' OR propType LIKE '%".$sst."%' OR pSType LIKE '%".$sst."%' OR createDate LIKE '%".$sst."%'";
}
$offset = 0;
}
if ($_SESSION['admin'] >= 1) {
$and = "";
}
else {
$and = "AND creatorID = '".$_SESSION['user']."'";
}

Related

do while loop php with multiple conditions

I am posting full code here for make my situation more clear.
<?php
require '../includes/env.php';
require '../includes/db.inc.php';
$total_campaigns = 0;
$total_checked_campaigns = 0;
$checked_campaigns_ids ="0";
$current_campaign_id = 0;
$c_rull = 1;
$c_daily_limit = 0;
/*get all live campaigns count*/
$total_campaigns = get_total_campaigns($conn);
/*check if any campaign available for send data*/
if($total_campaigns>0){
do {
//get one campaign id from all available campaigns.
$c_id = get_campaign($total_campaigns,$total_checked_campaigns,$checked_campaigns_ids,$current_campaign_id,$conn);
/*this while loop is checking that selected campaign have reached daily limit or not,if above campaign id reached limit, it should get another possible campaign id, if there no any campaign id avaialble
get_campaign function will return 0 and we will stop the loop*/
} while(!(($c_id == 0 || $total_checked_campaigns <= $total_campaigns) && is_daily_limit_allow($c_id,$c_daily_limit,$conn)));
echo $c_id;
}
function get_campaign($total_campaigns,$total_checked_campaigns,$checked_campaigns_ids,$current_campaign_id,$conn){
$c_status = 1;//live
$c_lead_status = 0;//not processed
$selectCampaignQuery = "SELECT * FROM tbl_software_campaigns WHERE c_lead_status = ? AND c_status = ? AND c_id > ? AND c_id NOT IN($checked_campaigns_ids) ORDER by c_id ASC LIMIT 1";
$stmt = $conn->prepare($selectCampaignQuery);
$stmt->bind_param("iii", $c_lead_status,$c_status, $current_campaign_id);
$stmt->execute();
$selectCampaignResult = $stmt->get_result();
if ($selectCampaignResult->num_rows==0) {
if($total_checked_campaigns==0){
$update_campaigns_query = "UPDATE tbl_software_campaigns SET c_lead_status = 0 WHERE c_status = 1";
$update_campaign_result = mysqli_query($conn,$update_campaigns_query);
$selectCampaignQuery = "SELECT * FROM tbl_software_campaigns WHERE c_lead_status = ? AND c_status = ? AND c_id > ? AND c_id NOT IN($checked_campaigns_ids) ORDER by c_id ASC LIMIT 1";
$stmt = $conn->prepare($selectCampaignQuery);
$stmt->bind_param("iii", $c_lead_status,$c_status, $current_campaign_id);
$stmt->execute();
$selectCampaignResult = $stmt->get_result();
}
}
if ($selectCampaignResult->num_rows>0) {
global $total_checked_campaigns;
global $c_daily_limit;
global $checked_campaigns_ids;
$row = mysqli_fetch_assoc($selectCampaignResult);
$c_id = $row['c_id'];
$c_daily_limit = $row['c_daily_limit'];
// we are updating total checked campaign count here as well updating comma seperated list of checked campaign id here in below two line
$total_checked_campaigns = $total_checked_campaigns+1;
$checked_campaigns_ids = $checked_campaigns_ids.",".$c_id;
//return campaign id for process the data
return $c_id;
}else{
//return 0 because there no any campaign available to process data
return 0;
}
}
function get_total_campaigns($conn){
$stmt = $conn->prepare("SELECT COUNT(c_id) AS total_campaigns FROM tbl_software_campaigns WHERE c_status = 1");
$stmt->execute();
$total_result = $stmt->get_result();
$row = mysqli_fetch_assoc($total_result);
$stmt->close();
return $row['total_campaigns'];
}
function is_duplicate($EMAIL,$conn){
$query = "SELECT lead_id FROM tbl_software_leads WHERE lead_email = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $EMAIL);
$stmt->execute();
$duplicate_result = $stmt->get_result();
$stmt->close();
if ($duplicate_result->num_rows>0){
return true;
}else{
return false;
}
}
function is_daily_limit_allow($CAMPAIGN,$LIMIT,$conn){
if($LIMIT>0){
$limit_query = "SELECT count(*) as today_total FROM tbl_software_leads WHERE DATE(lead_time)=CURDATE() AND lead_camp_id =? AND lead_status = 1";
$stmt = $conn->prepare($limit_query);
$stmt->bind_param('i',$CAMPAIGN);
$stmt->execute();
$limitrow = $stmt->get_result()->fetch_assoc();
$todaysrecord = $limitrow['today_total'];
if($todaysrecord<$LIMIT){
return true;
}else{
return false;
}
}else{
return true;
}
}
?>
Now Let me explain my goal.
What I am looking to do is
on start its checking how many campaigns available there!
if campaign available more than 0, I am getting one campaign id and marking that campaign as checked campaign using get_campaign function
get_campaign function giving me campaign id and if there no any campaign available for process, its give me 0 as id.
if there 0 as id, I do not want do anything since it means there no any campaign available for handle the data
if get_campaign give me any campaign id, I need to check that its reached daily limit or not with is_daily_limit_allow function, if its reached that limit, I need to get new id using get_campaign function and check its daily limit.
I am trying to achieve above thing with while loop but its not working properly and running for infinity time.
Basically when
if campaign id is 0, I want stop the loop
if total checked campaigns equal to total campaigns, I want stop the loop because it means we have checked all campaigns and none are available for process the data
if current campaign id allow to process data and have not daily limit, I want stop the loop.
I should also clear that when
$c_daily_limit = 0;
means there no any daily limit in that campaign.
I hope its clear everything now and will help to expert here on stackoverflow.
Let me know if anyone can help me for solve the puzzle.
Thanks!
You said
if campaign id is 0, I want stop the loop
if total checked campaigns equal to total campaigns, I want stop the loop because it means we have checked all campaigns and none are
available for process the data
if current campaign id allow to process data and have not daily limit, I want stop the loop.
So, it makes straightforward conditions as below,
while($c_id != 0 && $total_checked_campaigns < $total_campaigns && is_daily_limit_allow($c_id,$c_daily_limit,$conn));
Try below snippet once
do {
echo $c_id;
echo "<br>";
$c_id = get_campaign($total_campaigns);
} while (($c_id == 0 || $total_checked_campaigns <= $total_campaigns) && is_daily_limit_allow($c_id));
here I changed condiotions as per your trying to get
(($c_id == 0 || $total_checked_campaigns <= $total_campaigns) && is_daily_limit_allow($c_id))
as i understand can you try this code
do {
echo $c_id;
echo "<br>";
$c_id = get_campaign($total_campaigns);
} while (($c_id != 0 && $total_checked_campaigns <= $total_campaigns) || !is_daily_limit_allow($c_id));
or
while(!(($c_id == 0 || $total_checked_campaigns <= $total_campaigns) && is_daily_limit_allow($c_id)))

Alphabetically ordered list from mysqli join query

I am trying to print out an alphabetically ordered list of usernames after using a mysqli join query to select userid's from a friends table.
Friends table consists of
id - userid_one - userid_two - friendship_date - friendship_type
Users table has a pretty standard layout, and the only field I really need from it is the username (to display) and the userid to link the two tables
what i want to achieve is the below
A
Andy
Anna
B
Bobby
Brian
The code i am using is below.
$ir['userid'] //the current users id
$getfriends = mysqli_query($con,"SELECT * FROM friends INNER JOIN users ON (friends.userid_one = users.userid OR friends.userid_two = users.userid) WHERE (userid_one = '{$ir['userid']}' OR userid_two = '{$ir['userid']}') ORDER BY username") or die("query error");
$last="";
if(mysqli_num_rows($getfriends) == 0)
{
print"<li>You have no friends....sorry</li>";
}
else
{
while($gotf=mysqli_fetch_array($getfriends))
{
if($gotf['userid_one'] == $ir['userid']){$friend = $gotf['userid_two'];}else{$friend = $gotf['userid_one'];}
$printed_array = explode(",",$printed);
if(!in_array($friend,$printed_array))
{
$username_of_user = get_username_no_link($friend);
$current_letter = $username_of_user[0];
if ($last != $current_letter) {
print"<li class='Label'>{$current_letter}</li>";
$username_of_user = get_username_nd_avatar($friend);
print"<li>".$username_of_user."</li>";
$last = $current_letter;
$printed = $printed.",".$friend;
}
elseif($last == $current_letter){
$username_of_user = get_username_nd_avatar($friend);
print"<li>".$username_of_user."</li>";
$last = $current_letter;
$printed = $printed.",".$friend;
}
}
}
}
I have not got much experience of using JOIN in mysqli queries and my issue is that I am not getting the list sorted alphabetically as the below example shows.
A
Andy
T
Thomas
S
Sandra
Sally
UPDATE--
the order in which the usernames display, now seems to change randomly after reloading the page, which is further confusing the matter!
question now answered after some playing around. Ended up putting the usernames into an array, then sorting the array alphabetically by value, as well as adding a $printed_array array to add each friend to after they were printed to prevent them being printed out twice.
$usersnames = array();
while($gotf=mysqli_fetch_array($getfriends))
{
if($printed != ""){$comma = ",";}
if($gotf['userid_one'] == $ir['userid']){$friend = $gotf['userid_two'];}else{$friend = $gotf['userid_one'];}
$printed_array = explode(",",$printed);
if(!in_array($friend,$printed_array))
{
$username_of_user = get_username_no_link($friend);
$usersnames[] = $username_of_user;
$printed = $printed.$comma.$friend;
}
}
sort($usersnames);
foreach($usersnames as $name)
{
$getuserid = mysqli_query($con,"SELECT userid,avatar FROM users WHERE username = '$name' LIMIT 1");
$gotuserid = mysqli_fetch_array($getuserid);
//var_dump($gotuserid);
$displaypic = "<img style='height:30px;vertical-align:middle;margin:5px;' src='".$gotuserid['avatar']."'>";
$current_letter = $name[0];
if ($last != $current_letter)
{
print"<li class='Label'>{$current_letter}</li>";
print"<li><a href='profile/".$name."'>".$displaypic.$name."</a></li>";
$last = $current_letter;
}
elseif($last == $current_letter)
{
print"<li><a href='profile/".$name."'>".$displaypic.$name."</a></li>";
$last = $current_letter;
}
}

How to build a dynamic mysql query to suit all users

I need your help with my website search functionality. I'm developing a members area wherein users can search other registered users based on certain criteria, or combination of criteria.
My problem now is how to build a dynamic mysql query to suit the need of each combination of search criteria, where the number of criteria is variable.
Normally, I can write with a pre-determined set of criteria using
WHERE param1 = '$param1'
AND param2 = '$param2'
AND param3 = '$param3'
How do I solve this problem?
If the issue is that you don't know which of the criteria the user will pick, but want to return results for "blank" criteria, you can use the following:
$criteria_1 = $_POST['criteria_1'];
$criteria_2 = $_POST['criteria_2'];
$criteria_3 = $_POST['criteria_3'];
if(!$criteria_1 && !$criteria_2 && !$criteria_1) {
echo "You must select at least one criteria!";
} else {
// Run query mentioned below and return results.
}
THe query would then look like:
SELECT * from mytable
WHERE
(criteria1 = '$criteria_1' OR '$criteria_1' = '') AND
(criteria2 = '$criteria_2' OR '$criteria_2' = '') AND
(criteria3 = '$criteria_3' OR '$criteria_3' = '')
This will treat any blank (non-selected) parameters as blank and ignore them. Be aware that with the above, if no criteria are given, it will return all results.
Another way to write the above is:
SELECT * from mytable
WHERE
criteria1 IN ('$criteria_1', '') AND
criteria2 IN ('$criteria_2', '') AND
criteria3 IN ('$criteria_3', '')
Again, allowing for no entry at all to return all criteria1 results.
Here's a generic example of what you're asking:
$query = "SELECT * FROM mytable";
if ($_POST['name'] == "Jack") {
$query .= " WHERE name = 'Jack'";
}
if ($_POST['name'] == "Bob") {
$query .= " WHERE name = 'Bob'";
}
if ($_POST['state'] != "") {
$query .= " AND state = '" . mysql_real_escape_string($state) . "'";
}
//So now, in total, your query might look like this
//"SELECT * FROM mytable WHERE name = 'Bob' AND state = '$state'"
$result = mysql_query($query);
You just add to your $query string with if statements, then execute the query once you've checked all $_POST variables.
I've seen queries like this, so that if you don't want to put in a value for a particular column, you pass in NULL for that column:
SELECT *
FROM users
WHERE param1 = :param1
UNION
SELECT *
FROM users
WHERE param2 = :param2
UNION
SELECT *
FROM users
WHERE param3 = :param3
This assumes that you'll have each column indexed and you're performing Boolean AND searches (and using PDO).
use your scripting language (php) to loop over the inputs...
then have a structure like this:
WHERE 1=1
then add your
AND paramx = '$px'
to it...
$criteria = array();
//Populate your criteria and parameter arrays with input from the web page here
...
// $criteria should now have stuff in it
$sql = "SELECT * FROM mytable ";//Or whatever your sql query is
$count = 0;
foreach ($criteria as $key => $parameter) {
if ($count == 0) {
$sql = $sql."WHERE ".$key." = ".$parameter;
} else {
$sql = $sql."AND ".$key." = ".$parameter;
}
$count++;
}
That said, this is highly vulnerable to sql injection attack. Try using PHP PDO
An option is also to build the query from php/asp or whatever you working with, like this
$param1 = (isset($searchParam1) ? "param1 = $searchParam2" : "1");
$param2 = (isset($searchParam2) ? "param2 = $searchParam2" : "1");
$param3 = (isset($searchParam3) ? "param3 = $searchParam3" : "1");
and the query would be like
SELECT ... WHERE $param1 $param2 $param3
would like to share this code to build dynamic mysql query with PHP
Thx & regards
$vocabulary = (($page == "vocabulary") ? "image_name <> ''" : "");
$groupcat = (($group != "") ? "group = $group" : "");
$var = array($vocabulary, $groupcat);
$counter = "0";
$param = "";
for ($i=0;$i<count($var);$i++)
{
if ($counter == "0" && $var[$i] != "" ) $param = "WHERE ";
if ($counter > "0" && $var[$i] != "" ) $param = " AND ";
if ($param != "")
{
$condition .= $param . $var[$i];
$param="";
$counter++;
}
}
echo "Condition : ". $condition;

Pagination. Select from x number of tables

i'm trying to make my second website using php and i'm stuck at some typical problem (i believe),
but very hard for me.
I'm making a page that show list of items depends on GET.
#1 if only "type" sended - show all items with x type.
#2 if only "tag" sended - show all items with x tag.
#3 if "type" and "tag" sended at the same time - show all items with x type and x tag.
problem #1 i solved this way
// items per page
$per_page = 5;
// 1) if isset type
if ( (isset($_GET['type'])) && (!isset($_GET['tag'])) ){
$type_id = get_safe_var($_GET['type']);
$con = mysql_connect(DB_HOST,DB_LOGIN,DB_PASSWORD) or die(mysql_error());
if ($con) {
mysql_select_db(DB_NAME) or die(mysql_error());
$sql = mysql_query("SELECT `item_type`, `item_type_name` FROM `item_types` WHERE `type_id` = '$type_id'");
$row = mysql_fetch_assoc($sql);
$type = $row['item_type'];
$type_name = $row['item_type_name'];
if ($type != ''){
$pages_query = mysql_query("SELECT COUNT(`id`) FROM `".$type."` WHERE `insearch` = '1'");
$number_of_pages = ceil( mysql_result($pages_query, 0) / $per_page );
$current_page = ( (isset($_GET['page'])) && ((int)$_GET['page'] > 0) ) ? (int)$_GET['page'] : 1;
$start = ($current_page - 1) * $per_page;
echo "<h1>$type_name</h1>";
$sql = mysql_query("SELECT `id`, `name`, `img` FROM `".$type."` WHERE `insearch` = '1' ORDER BY `id` DESC LIMIT $start, $per_page");
// echo items
while ($row = mysql_fetch_assoc($sql)){
$id = $row['id'];
$name = $row['name'];
$img = $row['img'];
echo "
<div id='items_cell'>
<img alt='$name' src='$img' width='145' height='200' /><br />
<a href='open_item.php?type=$type_id&id=$id'>$name</a><br />
<em>$type_name</em>
</div>";
}
}
mysql_close($con);
} else {echo 'sql connection error';}
}
pagination
// echo pagination
// 1) if isset type
if ( (isset($_GET['type'])) && (!isset($_GET['tag'])) ){
if ( (isset($number_of_pages)) && ($number_of_pages >= 1) && ($current_page <= $number_of_pages) ){
for ($i = 1; $i <= $number_of_pages; $i++){
if ($i == $current_page){
echo "<li><a href='?type=$type_id&page=$i' class='sel'>$i</a></li>";
} else {
echo "<li><a href='?type=$type_id&page=$i'>$i</a></li>";
}
}
}
}
I'm stuck at problem #2.
I got tag ID. Need to show all items with that tag.
I don't understand how to make a SELECT from x-number of tables with a working paginatin.
database structure -
Any help is welcome!
P.S. Maybe i need to change db structure to make SELECT easier?
You should definitely work on your table design. Having dynamic table names is a big NO-NO as you won't ever be able to do any useful joins. Just create one big tag-table and add a column type like you did in your table item_types.
To solve problems #1-#3 just build the WHERE-part of your query dynamically:
// empty selection
$where = array();
if (!empty($_GET["type"])
$where[] = "`item_type` = '".mysql_real_escape_string($_GET["type"])."'";
if (!empty($_GET["tag"])
$where[] = "`tag` = '".mysql_real_escape_string($_GET["tag"])."'";
$query = "SELECT ... FROM `item`"
// Join type-table
. " JOIN `item_types` ON `item`.`id` = `item_types`.`item_id`"
// Join all of this item's tags
. " JOIN `item_tags` ON `item`.`id` = `item_tags`.`item_id`"
// Filter tags by item_type
. " AND `item_types`.`item_type` = `item_tags`.`item_type`"
;
if (count($where) > 0)
$query .= "WHERE ".implode(" AND ", $where);

SQL Construction & PHP

I'm sure this is an easy question.
If you want to produce SQL with php for a search query. So you have say 5 criteria which are all optional and may or may not be inputted by the user. You cannot guarantee any of them.
When it comes to making the SQL in php you can use :
So if they exist then you can use AND for the 4 last criteria.
But for the first criteria if you have that as a WHERE if that one is not selected then the SQL just is a list of ANDs with no starting WHERE.
Is there an easy answer?
Code I've Written :
$sql = "
SELECT *
FROM Request, Rooms
WHERE Day = ".$Day." ";
if($ModCode != ''){
$sql .="AND ModCode = ".$ModCode." ";
}
if($StartTime != ''){
$sql .="AND StartTime = ".$StartTime." ";
}
if($Length != ''){
$sql .="AND Length = ".$Length." ";
}
if($Room != ''){
$sql .="AND Request.RoomID = Rooms.RoomID ";
$sql .='AND Rooms.RoomName = "'.$Room.'" ';
}
if($Room == '' && $Park != ''){
$sql .="AND Request.RoomID = Rooms.RoomID ";
$sql .='AND Rooms.Park = "'.$Park.'" ';
}
And now I want the bit WHERE Day = $Day to be optional like the others.
Cheers
You could store all criterias in an array and then implode AND between them:
if(!empty($array)) {
$where_part = "WHERE " . implode(" AND ", $array);
}
Update:
$cond = array();
if($ModCode != ''){
$cond[] = "ModCode = ".$ModCode;
}
if($StartTime != ''){
$cond[] = "StartTime = ".$StartTime;
}
if($Length != ''){
$cond[] = "Length = ".$Length;
}
if($Room != ''){
$cond[] = "Request.RoomID = Rooms.RoomID";
$cond[] = 'Rooms.RoomName = "'.$Room.'"';
}
if($Room == '' && $Park != ''){
$cond[] = "Request.RoomID = Rooms.RoomID";
$cond[] = 'Rooms.Park = "'.$Park.'"';
}
if(!empty($cond)) {
sql .= "WHERE " . implode(" AND ", $cond);
}
I dont think this would work.
For this kind of JOIN you always need a WHERE statement with a join condition.
And after adding it, the question will make sense no more.
However, if you need conditional JOIN as well as conditional WHERE, you had to state it in the question.
Anyway, the method is quite similar.
Store your wheres in an array and only impode the array into the query if its not empty.
Something like this;
$where = array();
//build up your where's in an array
$where[] = "searchField1='blah'";
$where[] = "searchField2='foo'";
//make your query and on the where only implode the array if its not empty else return null
$sqlQuery = "
Select
*
FROM
yourTable
".(empty($where)==false ? " WHERE ".implode(" AND ", $where) : null)."
ORDER BY x
";
where 1 = 1
and (name = ? or ? is null)
and (age = ? or ? is null)
question marks are just value placeholders. you get the point.
use prepared statements and bound parameters.
anyway, each of the parenthesized predicate conditions will evaluate to true of the placeholder value is null. make sure you differentiate between the sql keyword null, and "empty" or "falsy" values like 0 or empty string. The above requires type null.
I think I understand what you mean. You could split the query like so.
$sql = "SELECT * FROM `table` WHERE ";
$sql .= ($val1 == 1) ? "`field` = 'value' " : "1 = 1 ";
$sql .= ($val2 == 2) ? "AND `field` = 'value'" : "AND 1 = 1";
Edit: A quick fix would be to add a clause that would always be true.
In MySQL you have MATCH ... AGAINST
Like so:
SELECT id, header, message FROM table WHERE MATCH(header,message) AGAINST ('".mysql_real_escape_string($search)."' IN BOOLEAN MODE)
You can combine MATCH .. AGAINST with any other WHERE-clause, like:
WHERE id > 1000 AND MATCH (...) AGAINST ('searchstring' IN BOOLEAN MODE) AND date < NOW()
This does, however, require FULLTEXT searches to be possible, so it isn't very useful on TEXT-columns in InnoDB-tables for as far as I know. But it is the perfect solution to do searches in MyISAM tables, and you can use it on VARCHAR()-columns.

Categories