在时间戳字段中按日期过滤结果

时间:2013-11-14 20:46:51

标签: php mysql database timestamp

我已经得到了一些帮助,但不确定为什么这不起作用。

我正在尝试使用表单让用户过滤他们的活动(存储在数据库中)

我的代码:

$_GET['from'] = '01/11/2013';
$_GET['to']   = '25/11/2013';

$from = DateTime::createFromFormat('d/m/Y', $_GET['from']);
$to   = DateTime::createFromFormat('d/m/Y', $_GET['to']);

$sql = "
    SELECT * FROM transfer 
    WHERE personID = $user AND DATE(time) BETWEEN '%s' AND '%s'
";
$sql = sprintf($sql, $from->format('Y-m-d'), $to->format('Y-m-d'));

print_r($sql);

这打印 SELECT * FROM transfer WHERE personID = 84587749 AND DATE(time) BETWEEN '2013-11-01' AND '2013-11-14'

当我在PHPmyadmin中查询时,它显示了记录,但是没有显示在我的页面中?

2 个答案:

答案 0 :(得分:1)

SQL看起来很好但你似乎没有在数据库中发出执行SQL查询并检索结果?也许我错过了一些东西,但你需要连接到你的数据库:

class DBi {
  public static $mysqli;
}

DBi::$mysqli = new mysqli('servername', 'database', 'password', 'user');

if (mysqli_connect_error()) {
  die('Connect Error (' . mysqli_connect_errno() . ') '
        . mysqli_connect_error());
}

然后你需要执行查询:

$result = DBi::$mysqli->query($sql) or die ("Unable to execute SQL command:".$sql);

最后,检索并使用结果:

$row = $result->fetch_assoc();
echo $row["fieldname"];

答案 1 :(得分:0)

以下是打印结果的示例。

$dbserver = "localhost";
$dbname = "nameofDB";
$dbusername = "username";
$dbpassword = "password";

$mysqli = new mysqli($dbserver, $dbusername, $dbpassword, $dbname);

$query = "SELECT * FROM transfer WHERE personID = 84587749 AND DATE(time) BETWEEN ? AND ?";

if($stmt = $mysqli->prepare($query)){

    /*
    Binds variables to prepared statement

    i    corresponding variable has type integer
    d    corresponding variable has type double
    s    corresponding variable has type string
    b    corresponding variable is a blob and will be sent in packets
    */

   $to = $_POST['to'];
   $from = $_POST['from'];

   $stmt->bind_param('ss', $from, $to);


   /* execute query */
   $stmt->execute();

   /* Get the result */
   $result = $stmt->get_result();

   while ($row = $result->fetch_assoc()) {
        // Configure this how you want to print out each row.
        echo 'Details: '.$row['details'].'<br>';
        echo 'Time: '.$row['time'].'<br>';
        echo 'Balance: '.$row['balance'].'<br>';
        echo '<br><br>';
   }

   /* free results */
   $stmt->free_result();

   /* close statement */
   $stmt->close();
}

/* close connection */
$mysqli->close();