如何通过使用where子句获取范围之间的值

时间:2018-11-20 06:56:53

标签: php mysql codeigniter select

数据库结构enter image description here我正在尝试在控制器(Codeigniter)中进行原始查询,并且试图从用户在newDate和newDate2上提供的范围中获取值。我的问题是它什么也不显示。我该如何写查询。.我只想根据voucherno(vno)显示数量,产品名称,捆绑...这是我尝试过的代码

控制器代码:

$startdate         = $this->input->post('SDate');
$enddate           = $this->input->post('EDate');
$date              = str_replace('/', '-', $startdate);
$newDate           = date("Y-m-d", strtotime($date));
$date2             = str_replace('/', '-', $enddate);
$newDate2          = date("Y-m-d", strtotime($date2));
$data['startdate'] = $startdate;
$data['enddate']   = $enddate;
$query             = $this->db->query('SELECT `vno`,`Prdtname`,`Qty`,`bundle` FROM purchaseitem WHERE billdate >= "$newDate"AND billdate <= "$newDate2" ORDER by `vno`')->result_array();
$data['query']     = $query;

查看代码:

<?php foreach ($query as $row): ?>
                                            <tr><td></td><td></td><td></td><td></td>
                                        <td><?=$row['Prdtname'];?></td>
                                        <td><?=$row['Qty'];?></td>
                                        <td><?=$row['bundle'];?></td>

                                        <?php endforeach ?> 

4 个答案:

答案 0 :(得分:4)

将您的查询更改为以下查询并进行检查。

您必须以单引号或双引号括住日期。

$query = $this->db->query('SELECT `vno`,`Prdtname`,`Qty`,`bundle` FROM purchaseitem WHERE billdate >= "'.$newDate.'" AND billdate <= "'.$newDate2.'" ORDER by `vno`')->result_array();

让我知道是否仍然存在问题。

答案 1 :(得分:0)

您可以使用Between

SELECT `vno`,`Prdtname`,`Qty`,`bundle` FROM purchaseitem WHERE billdate BETWEEN "$newDate" AND "$newDate2" ORDER by `vno`

答案 2 :(得分:0)

如果仅存储日期,则尝试使用Unix时间戳。

$snewsDate = strtotimr($startdate);
$newDate2 = strtotime($enddate);

SELECT `vno`,`Prdtname`,`Qty`,`bundle` FROM purchaseitem WHERE billdate BETWEEN 
UNIX_TIMESTAMP($newDate) AND UNIX_TIMESTAMP($newDate2) ORDER by `vno

答案 3 :(得分:0)

尝试这个:

$startdate         = $this->input->post('SDate');
$enddate           = $this->input->post('EDate');
$newDate           = date_format(date_create($startdate),"Y-m-d");
$newDate2          = date_format(date_create($enddate),"Y-m-d");
$data['startdate'] = $startdate;
$data['enddate']   = $enddate;
$query             = $this->db->query("SELECT vno,Prdtname,Qty,bundle FROM purchaseitem WHERE billdate BETWEEN '$newDate' AND '$newDate2' ORDER by vno")->result_array();
$data['query']     = $query;