Can not compare two date using PHP [duplicate] - php

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'])))

Related

last element in while loop php [duplicate]

This question already has answers here:
Removing last comma from a foreach loop
(9 answers)
Closed 5 years ago.
$result = $conn->query("SELECT * FROM mails");
while($row = $result->fetch_assoc()){
$mymail= $row['mail']. ",";
echo $mymail;
}
I have after every row comma (,) but I don't want (,) after last row. How could I do this?
Take a look at the join function:
$mails = array();
$result = $conn->query("SELECT * FROM mails");
while($row = $result->fetch_assoc())
{
$mails[] = $row['mail']; // Store E-Mail adresses in an array
}
$commaSeparatedMails = join(',', $mails); // Connect all array parts using a comma
echo $commaSeparatedMails;
rtrim(yourstring,","), this function will remove right comma.

Format string in PHP [duplicate]

This question already has answers here:
How to get the last dir from a path in a string
(11 answers)
How to obtain the last word of a string
(8 answers)
Closed 7 years ago.
I have below code, which gets me file path as voicetube/record/1985150721112615
but I need only 1985150721112615 exploding first two folders,please help me on this
$sql = "SELECT filePath FROM user_recordings ORDER BY recordDate ASC";
$result = mysql_query($sql);
$var = array();
while ($row = mysql_fetch_array($result))
{
$var[] = $row['filePath'];
}
You are looking for basename();
$var[] = basename($row['filePath']);
You can use explode function, and grab it's last index.
while ($row = mysql_fetch_array($result))
{
$arr = explode('/', $row['filePath']);
$var[] = $arr[count($arr) -1];
}

php sql statment for multiple conditions proper approch

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;
}

This php string joining is driving me crazy!

I want to prepend a "0" in front of a $_POST
$currency = $_POST['Currency']; // lets say 900
$currency = "0".$currency;
echo $currency;
It should have returned 0900 but it returns 900.
Any ideas?
EDIT
This is the full function
function validate(){
$ref = $this->input->post('Ref');
$shop = $this->input->post('Shop');
$amount = $this->input->post('Amount')*1000;
//$currency = $this->input->post('Currency');
//$currency = $_POST['Currency']; // lets say 900
//$currency = "0".$currency;
$currency = str_pad($_POST['Currency'],4,'0',STR_PAD_LEFT);
$query = $this->db->query("SELECT * FROM shop_validation WHERE merchant_ref = '$ref' ");
if($query->num_rows() > 0) {
$row = $query->row_array();
$posts = "";
foreach ($_POST as $name => $value) {
$posts .= $name." / ".$value;
}
$this->db->query("INSERT INTO transactions (shop,amount,currency,posts) VALUES ('$shop','$amount','$currency','$posts')");
if($row['merchant_ref'] != $ref)
{
echo "[NOTOK]";
return;
}
if($row['merchant_id'] != $shop)
{
echo "[NOTOK]";
return;
}
if(trim($row['amount']) != $amount)
{
echo "[NOTOK]";
return;
}
if($row['currency_code'] != $currency)
{
echo "[NOTOK]";
return;
}
echo "[OK]";
}
}
EDIT
This script run on Codeigniter framework
If what you want is to ensure that the input has a set number of digits, with leading zeros, I wrote a tip some time ago that does exactly that:
<?php
$variable = sprintf("%04d",$_POST['Currency']);
?>
This, will echo leading zeros until the $variable is 4 characters long. Here are some examples:
If $_POST['Currency'] has a value of
'3' it would echo '0003'
If $_POST['Currency'] has a value of
'103' it would echo '0103'
If $_POST['Currency'] has a value of
'3103' it would echo '3103'
Which is good even if the amount of characters is longer than 4 (in your case) since it would simply ignore the function and not add anything in front of it. Hope it helped :)
You might want to use the PHP's str_pad() function like that
$currency = str_pad($_POST['currency'],4,'0',STR_PAD_LEFT)
See php manual for details
Your problem is auto-casting, where a variable can be a string or a number value and php guesses which one you cant. Your currency variable is being used as a string when you do string contatenation on it with the dot operator, but then when you echo it it assumes it to be an integer and throws you the integer value. You could echo (string)$currency or use the str_pad() or printf() function to get more useful output values.
EDIT: The code in the question actually works as expected for me. You must be simplifying the example and your actual output function is something other than what you present here, because in that code the auto typecasting stuff works fine.

How do I get max(); to display the highest value number rather than just "Array"?

max($caption);
gives me this:
Array
$caption is defined here:
$i = "0";
while ($i < $count) {
list($oldCaption, $year, $order) = explode("-", $galleryDirectory[$i]);
$caption[$year][$order] = str_replace("_", " ", "$oldCaption");
echo $year; //debug
echo "<br />";
$i++;
}
$year comes out to be
2008
2009
2009
so how do I get max($caption); to give me the value of 2009 rather than Array?
also i would put the whole code, but when i tried that it turned out messy. but I will try again, so you guys can see the whole pictures
Use array_keys():
$years = array_keys($caption);
$maxYear = max($years);
// or the one-liner:
$maxYear = max(array_keys($caption));
The reason why your code wasn't working is that you were comparing the values of the array $caption, which is an another array. max() compares int values, not keys nor arrays. By using array_keys() on $caption creates another array with all years as values.

Categories