从mysql中的列中获取数据

时间:2014-07-06 09:59:09

标签: php mysql sql

我想只获取那些列(名称时间和类型时间戳)大于某个时间戳并且小于某个时间戳的行...我使用下面写的这段代码但它给了我错误..我想要知道是不是sql语法

<?php
include_once'header.php';
$time=$_GET['t'];
$prev=$_GET['prev'];
$q="SELECT * FROM comment WHERE time<'$time' AND time >'$prev' ";
$r=mysql_query($q);
while($row=mysql_fetch_array($r))
{
echo "<p>".$row[4]."</p>";
}

?>

2 个答案:

答案 0 :(得分:0)

你是否与mysql建立了连接

$conn = New mysqli(SERVER, USER, PASS, NAME);
if (!$conn)
{
die("Database connection failed: " . mysqli_error());
}
$result = $conn->query("SELECT * FROM comment WHERE time<'".$time."' AND time >'".$prev."' ");
while($row = mysqli_fetch_array($result))
{
echo "<p>".$row[4]."</p>";
echo "<br>";
} 

答案 1 :(得分:0)

(摘自http://www.php.net/manual

    $firstname = 'fred'; $lastname  = 'fox';

    // Formulate Query 
    // This is the best way to perform a SQL query 
    // For more examples, see mysql_real_escape_string() 
    $query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
        mysql_real_escape_string($firstname),
        mysql_real_escape_string($lastname));

    // Perform Query $result = mysql_query($query);

    // Use result
    // Attempting to print $result won't allow access to information in the resource
    // One of the mysql result functions must be used
    // See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
    while ($row = mysql_fetch_assoc($result)) {
        echo $row['firstname'];
        echo $row['lastname'];
        echo $row['address'];
        echo $row['age'];
    }

这里的要点是,您不应在查询中使用未转义的表达式,因为它们可以提供SQL注入的方法。

此外,在您的特定查询中,您可以使用sql关键字BETWEEN:

$q=sprintf("SELECT * FROM comment WHERE time BETWEEN '%s' AND '%s'",
   mysql_real_escape_string($prev),
   mysql_real_escape_string($time));

另请注意,不推荐使用mysql_query,请尝试使用mysqli_query。