i am trying to write one function which return sql statement
like
function get_sql($name=0,$date_start=0,$date_end=0)
{
$addQuery=" where 1=1";
if($name>0)
{
$addQuery .=" and name=".$name;
}
if($date_start>0)
{
$addQuery.=" and date >=".$date_start;
}
if($date_end >0)
{
$addQuery.=" and date<=".$date_end;
}
$query="select * from TABLE_ARTICLE".$addQuery;
return $query;
}
sorry guys for wrong syntax typing
i have two concerns about this function.
does this is proper approach or not?
does this function will work when date will be passed in 01/03/2012 format, as you can see i want result between two dates if both are selected and after first date or before end date ?
i mean does this is best way to get data from sql in dates?
Thanks for helping
You might be better off using implode
function get_sql($name=0,$date_start=0,$date_end=0)
{
$whereClauses = array();
if($name>0)
{
$whereClauses[] = "name='$name'";
}
if($date_start>0)
{
$whereClauses[] = "date >='$date_start'";
}
if($date_end >0)
{
$whereClauses[] = "date<='$date_end'";
}
$query="select * from TABLE_ARTICLE";
if( !empty( $whereClauses ) )
{
$query.= ' WHERE ' . implode( ' AND ', $whereClauses );
}
return $query;
}
Note also that I have quoted all your values as none of them seem to be integer values.
As regards the date format, MySQL will not recognise the format you state. You will need to provide the dates in YYYY-MM-DD (or possibly unix timestamp) formats to MySQL.
1) No. You're overwriting the string. I think you mean $blah .= 'blah';
2) Nope. It won't be in quotes so MySQL will try to parse it as either a number or an entity name. Then, if it were in quotes, it would be an invalidly formatted date for MySQL.
date() is your friend.
Oh, and also, in SQL it's 1 = 1, not 1 == 1. And really that's not necessary to use here, though I guess it sort of makes the string building easier. (I would probably build an array and implode it, but that would be slower/more complex.)
1) use "=" instead of "=="
$addQuery=" where 1==1"; => $addQuery=" where 1=1";
2) quote values properly if they are string or char type :
$addQuery=" and name=".$name; => $addQuery=" and name='".$name."'";
3) check date formates in your database table and php variable make them same using date_format() or date()
functions.
4)if your want to check all condition at a time then do proper concatenation like:
if($name>0) { $addQuery.=" and name=".$name; }
if($date_start>0){ $addQuery.=" and date >=".$date_start; }
......
You need to append additional conditions to $addquery, so you must do as below :
$addQuery .=" and name=".$name;
$addQuery .=" and date >=".$date_start;
$addQuery .=" and date<=".$date_end;
This is how I'd do it:
function get_sql($name = null, $date_start = null, $date_end = null)
{
$where = array();
if($name !== null)
{
$where[] = "name='".mysql_real_escape_string($name)."'";
}
if($date_start !== null)
{
$where[] = "date >= STR_TO_DATE('".$date_start."', '%d/%m/%Y')";
}
if($date_end !== null)
{
$where[] = "date <= STR_TO_DATE('".$date_end."', '%d/%m/%Y')";
}
$query = "select * from TABLE_ARTICLE";
if( count($where) > 0 ) {
$query .= " WHERE ".implode(' AND ', $where);
}
return $query;
}
Related
I have a code in php it takes a well formatted string such as 'field,operator,value' and produces a WHERE statement to MySQL database query.
if the two fields names below end with the same characters such as '*id' such as 'id' and 'classid' it produces strange behavior. such as the following:
$where = $_GET['where'];
$tokens = multiexplode(array("^", "~", "(", ")"), $where);
$where = str_replace("^", " AND ", $where);
foreach ($tokens as $item) {
if (!empty($item)) {
$where = str_replace($item, getOperand($item), $where);
}
}
echo 'WHERE '.$where;
function multiexplode($delimiters, $string)
{
$unifydelimters = str_replace($delimiters, $delimiters[0], $string);
$conditions = explode($delimiters[0], $unifydelimters);
return $conditions;
}
function getOperand($item)
{
$extokens = explode (",", $item);
switch (trim($extokens[1])) {
case 'eq':
return trim($extokens[0]) . " = '" . trim($extokens[2]) . "' ";
break;
default:
return "";
break;
}
}
tested with :
http://localhost/test/test.php?where=id,eq,1^classid,eq,19
ALways show: id = '1' AND classid='1' 9
Not: id = '1' AND classid='19'
But if any other field ends differently from the other such as:
http://localhost/test/test.php?where=id,eq,1^class,eq,19
It correctly shows: id = '1' AND class='19'
Any idea why this is happening??
Thanks,
The problem is that when you search for the first expression id,eq,1 for the replacement in the string
id,eq,1^classid,eq,19
You will find two positions:
id,eq,1^classid,eq,19
^ ^
id,eq,1 |
id,eq,1
This means you will do two replacements, even though you wanted only replace one.
To solve this problem you don't need to work with the original input string $where. Instead you can use the already create array in $tokens and change the individual array elements. You can use array_map() to do that, like this:
$changed = array_map('getOperand', $tokens);
Then you can put the array together to a string with ' AND ' as the separator:
$result = implode(' AND ', $changed);
This will finally generate the following result:
id = '1' AND classid = '19'
Keep in mind that you should use prepared statements to avoid SQL injections, see How can I prevent SQL injection in PHP?
I am trying to craft a multiword search that will query multiple columns in a table. My code works great thus far for a single column, but as you can imagine using it for more then one column becomes an issue.
If I add orWhere it won't work, and I don't really want to create more for loops because it will become quite cumbersome. Any Ideas?
$query = $request->getParameter("article-search");
$keywords = explode(" ", $query);
for( $i = 1; $i <= count( $keywords ); $i++ ){
$q->addWhere("a.title LIKE ?", "%" . $keywords[$i - 1] . "%");
}
I just did it like this.. Maybe it helps somebody..
$now = "some other parameter";
$parts = explode(" ",trim($searchtext));
$clauses=array();
// static paramtter setted here
$parameters = array(
':now' => $now
);
$i = 0;
foreach ($parts as $part){
// for every word make new search query and parameter
$parameters[":param".$i] = "%".$part."%";
if($i == 0){
$clauses = "v.description LIKE :param".$i." OR v.name LIKE :param".$i." OR v.sale LIKE :param".$i;
} else {
$clauses .= " OR v.description LIKE :param".$i." OR v.name LIKE :param".$i." OR v.sale LIKE :param".$i;
}
$i ++;
}
$qb->select('v')
->from('MyBundle\Entity\Voucher', 'v')
->where('v.date_start <= :now')
->andWhere('v.date_end >= :now')
->andWhere($clauses)
->setParameters($parameters);
Usually I would write this as a query that looks something like the following:
$query = "`where column like '%$keywordOne%' or column like '%keywordTwo%'`";
Though I'm not sure how you implement that with the query-building tool you have there.
Here's a quick example that might help build the where portion of the query using the array of keywords you have:
<?php
$keywords = array("bing", "bang", "jump");
$query_start = 'where colummName';
$like_portion = "like '%" . implode("%' or columnName like '%", $keywords) . "%'";
if(sizeof($keywords) > 0) {
echo "`$query_start $like_portion`";
} else {
// No keywords
}
?>
Let me know if there's anything I can clarify here
Maybe you can consider using "union"? Also, for such complex queries, I would use native SQL instead of ORM practice.
This question already has answers here:
How to compare two dates in php [duplicate]
(16 answers)
Closed 7 years ago.
I have an issue while comparing two date inside if condition. I am providing my code below.
$erresult = mysqli_fetch_array($qrylast);
$ticket = $erresult['ticket_id'];
if ((date("Y-m-d") == $erresult['date'])) {
$id = sprintf("%03d", $ticket++);
$fields = array("date", "ticket_id ");
$tablename = "db_ticket";
$values = array(date("Y-m-d"), $id);
$id1 = db_insert($tablename, $values, $fields);
if ($id1) {
$ticket_id = 'W1' . date("Ymd") . $id;
}
} else {
$id = '001';
$fields = array("date", "ticket_id ");
$tablename = "db_ticket";
$values = array(date("Y-m-d"), $id);
$id1 = db_insert($tablename, $values, $fields);
if ($id1) {
$ticket_id = 'W1' . date("Ymd") . $id;
}
}
Here I need to compare today's date with date save inside database. My saved date inside database datatype is also date but here always else part is executing. In my code I have one condition (date("Y-m-d")==$erresult['date']) and this condition is never executing even two date are same.
Try
if(strtotime(date("Y-m-d")) == strtotime($erresult['date']))
follow :- How to compare two dates in php
You can use the strtotime() function to compare the two dates
e.g
if(strtotime(date("Y-m-d")) == strtotime(date("Y-m-d",$erresult['date'])))
This question already has answers here:
How can I bind an array of strings with a mysqli prepared statement?
(7 answers)
Closed 6 months ago.
I have a string like this 'dubai,sharjah,' and I want to make it like this 'dubai','sharja',
I am passing the value dubai,sharjah, in the URL using ajax and my code
$city=$_GET['city'];
$sql = "SELECT * FROM filter where isdeleted = 0 ";
if ($city !="" && $city !="Empty" ){
$sql.=" and twon in ('".$citydata."')";
}
when I print the query, it's like this
SELECT * FROM filter where isdeleted = 0 and twon in ('dubai,sharjah,')
but I want it like this
SELECT * FROM filter where isdeleted = 0 and twon in ('dubai','sharja')
Can anyone guide me on how to do this using PHP?
Here's how I would approach it. I'm going to use PDO instead of mysqli because trying to get an array into mysqli_stmt::bind_param is just a pain.
First, create an array of cities, removing any empty values
$params = array_filter(explode(',', $city), function($c) {
return !empty($c) && $c !== 'Empty';
});
$paramCount = count($params);
$query = 'SELECT * FROM filter where isdeleted = 0';
Now generate a placeholder string for your prepared statement.
if ($paramCount) {
$placeholders = implode(',', array_fill(0, $paramCount, '?');
// looks something like '?,?'
$query .= " AND twon IN ($placeholders)";
}
Now, prepare a statement
// assuming you have a PDO instance in $pdo created with something like
// $pdo = new PDO('mysql:host=localhost;dbname=your_db;charset=utf8', 'username', 'password', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $pdo->prepare($query);
Execute and fetch values :)
$stmt->execute($params);
$filters = $stmt->fetchAll(PDO::FETCH_ASSOC);
$cities = explode(",", $_GET['city']);
//escape!
foreach ($cities as $citykey => $city) {
$cities[$citykey] = "'" . mysql_real_escape_string($city) . "'";
}
$sql = "SELECT * FROM `filter` where `isdeleted` = 0";
if (!empty($cities)) {
$sql .= ' and `twon` in (' . implode(',', $cities) . ')';
}
An alternative is to use FIND_IN_SET(). No PHP code change needed.
$sql.=" and FIND_IN_SET(town, '".$citydata."')";
you can try to explode the string
$cityparts = explode(",",$city);
and you can use
$cityparts[0] and $cityparts[1] in your query
array explode ( string $delimiter , string $string [, int $limit ] )
you can find more information on [http://www.php.net/explode]
hope this helps!!
You just have to explode and implode here. Rest is the problem with extra , in your string at the end.
$str = "dubai,sharjah,";
$citydata = implode("','",explode(',',rtrim($str,',')));
echo "'$citydata'";
test
After 6 answers I gotta add a 7th:
$sql.=" and twon in ('".str_replace(",","','",$citydata)."')";
You can do this.
$string = 'dubai,sharjah';
$cities = explode(',', $string);
echo $cities[0]; //dubai
echo $cities[1]; //sharjah
try this
$str = "dubai,sharjah,";
$arr = explode(",", $str);
$arr_temp = array()
foreach($arr as $s)
{
if($s!="")
{
$arr_temp[] = "'".$s."'";
}
}
$new_str = implode(",", $arr_temp);
echo $new_str; // output 'dubai','sharjah'
Now your Sql will be
$sql = "SELECT * FROM filter where isdeleted = 0 and twon in ($new_str) ";
You can use it
in $city I fix two values with, you can use here by $_GET ;
$city = "dubai,sharjah,";
$query_string ="";
$words = explode(",",$city);
for($i=0;$i<count($words);$i++){$query_string .= "'".$words[$i]."',";}
$query_string = substr($query_string,0,strlen($query_string)-4);
then use your query
SELECT * FROM filter where isdeleted = 0 and twon in ($query_string)
if ($city !="" && $city !="Empty" )
{
$city_exp = explode(',' $city);
$sql .= " and twon in ('".implode("', '", $city_exp)."')";
}
What we are basically doing here is putting the two values in an array by using explode and then separating each item in that array by using implode
DEMO
$query="INSERT INTO subscriber (RandomCode,Email,CreateDate,UpdateDate <?if ($num!=0) echo ','.$string; ?> ) VALUES (?,?,?,?,CURDATE(),'',<? if ($num!=0) echo ','.$stringResult; ?>)";
echo $query;
If i add something conditional in the sql statement , it will not check or trigger the php function.
if (!isset($set['Attribute']))
{$set['Attribute']=NULL;} <=======This statement to check if there is no value posted
$stringResult=$stringResult.$_POST[$set['Attribute']].",";}}
$stringResult = substr($stringResult, 0, -1);
echo $stringResult;
Also, if a result is a null value posted, how can i set it so that it can be view in stringResult as '' ? I need to put it in my sql statement.
Thank you.
$query="INSERT INTO subscriber (RandomCode,Email,CreateDate,UpdateDate <?if ($num!=0) echo ','.$string; ?> ) VALUES (?,?,?,?,CURDATE(),'',<? if ($num!=0) echo ','.$stringResult; ?>)";
This is broken; you don't echo to add to a string, you need to concatenate it together. Here's how:
$query="INSERT INTO subscriber (RandomCode,Email,CreateDate,UpdateDate";
if ($num!=0)
{
$query .= ',' . $string;
}
$query .= ") VALUES (?,?,?,?,CURDATE(),'',"
if ($num!=0)
{
$query .= ','.$stringResult;
}
$query .= ")";
When you are guilding a string and need to stop and make a decision, like "is this zero? then do this, now continue on.", you need to end the string, concatenate a string into it if need be, and then concatenate the rest of the string onto the end. Continue ending the string and concatenating parts on until you are done.
If you are adding a null value to a string, it's the same as adding an empty string - ''.
$string "mystring" . NULL . "morestring"; //result is "mystringmorestring"
$string "mystring" . "" . "morestring"; //result is "mystringmorestring"
The resulting string is exactly the same. While NULL !== "" (meaning NULL and "" are not identical because they are not the same type), as far as the resulting string goes, it's the same.
The problem you have is that you're trying to open <?php ?> when you're already in PHP. The string will be output as-is to the mysql handler. What you'll want to do instead is simply set a variable and then just add the result into your string.
$firstAddition = ($num!=0) ? ','.$string : '';
$secondAddition = ($num!=0) ? ','.$stringResult : '';
And then, when you build your query, simply concatenate in those new variables.
You could use an inline ternary:
$str = 'abcd' . ($num != 0 ? ',' : '' ) . 'efg';
Otherwise, just break it up with if statements:
$query = "INSERT INTO subscriber (RandomCode, Email, CreateDate, UpdateDate ";
if ($num != 0) {
$query .= ', ' . $string;
}
$query .= ") VALUES (?, ?, ?, ?, CURDATE(), ''";
if ($num != 0) {
$query .= ', ' . $stringResult;
}
$query .= ")";
I'd put the conditional above the line where I set the query.
<?php
$extra='';
if ($num!=0) $extra= ','.$string;
$extra2='';
if ($num!=0) $extra=','.$stringResult;
$query="INSERT INTO subscriber (RandomCode,Email,CreateDate,UpdateDate '.$extra.' ) VALUES (?,?,?,?,CURDATE(),'','.$extra2.')";
?>
Completely untested. Be sure you sanitize $string and $stringResult.