I want to know how or if I can use the content of a column in mysql as a key (index) to a php array within the mysql query.
Example:
Column name: period
Column contents: (one of) 'Year','Month','Fortnight','Week','Hour','Day'
My php array:
$x = array(
'Year' => 1,
'Month' => 12,
'Fortnight' => 26,
'Week' => 52,
'Hour' => 1872,
'Day' => 365
);
Another variable $y can be any number (say < 1,000,000)
I want to write a WHERE (or HAVING) condition such as...
WHERE '$x[`period`]' * '$y' > 12345
Eg when the contents of period = 'Month', $y should be multiplied by 12 before being tested to be > 12345
What is the best (most efficient) way to do this, other than (say) a long CASE conditional?
Thank you
i have write demo query
<?php
$x = array(
'Year' => 1,
'Month' => 12,
'Fortnight' => 26,
'Week' => 52,
'Hour' => 1872,
'Day' => 365
);
$y=10;
$sql="select * from table where ".$x['Month']*$y." > 12345" ;
echo $sql;
in $x[]
select your value to multiply
You can use case
instead of php array:
<?php
$y = 100;
$sql = "select * from tablename
where (case `period`
when 'Year' then 1
when 'Month' then 12
when 'Fortnight' then 26
when 'Week' then 52
when 'Hour' then 1872
when 'Day' then 365
end) * {$y} > 12345";
Try this:
<?php
$y = 10;
$period = "Month";
$x = array(
'Year' => 1,
'Month' => 12,
'Fortnight' => 26,
'Week' => 52,
'Hour' => 1872,
'Day' => 365
);
$sql="select * from table where ".($x[$period] * $y)." > 12345" ;
echo $sql;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.