简单的PHP MYSQL select语句不返回任何内容

时间:2017-07-22 03:37:47

标签: php mysql

好吧,所以我有一个带有一个表的简单数据库,我有一个函数可以获取该表的所有行:

function get_days() {
    global $db;
    $query = 'SELECT * FROM days'
            . 'ORDER BY idDays';
    $statement = $db ->prepare($query);
    $statement ->execute();
    $the_days = $statement->fetchAll();
    //$statement->closeCursor();
    return $the_days;
    //return $statement;
}

我已经检查了其他所有内容,其他一切功能都很好,包括我将网站输入数据的网站部分,插入语句工作得很好,所以我把它缩小到这一个选择语句。

3 个答案:

答案 0 :(得分:1)

问题出在SQL语法中。你应该这样做:

function get_days() {
    global $db;
    $query = 'SELECT * FROM days '
            . 'ORDER BY id';
    $statement = $db ->prepare($query);
    $statement ->execute();
    $the_days = $statement->fetchAll();
    //$statement->closeCursor();
    return $the_days;
    //return $statement;
}

答案 1 :(得分:1)

问题是查询的字符串连接:

$query = 'SELECT * FROM days' . 'ORDER BY idDays';

这导致:SELECT * FROM daysORDER BY idDays

请改为包含空格字符:

$query = 'SELECT * FROM days' . ' ORDER BY idDays';

您可以通过正确的错误处理来避免此类问题:

try{
    $statement->execute();
}
catch(PDOException $e){
    exit($e->getMessage());
}

您可能还想删除以下位置:

$db ->prepare($query);
$statement ->execute();

所以他们变成了:

$db->prepare($query);
$statement->execute();

答案 2 :(得分:1)

这是一种简单的方法来选择你可以使用它的功能。

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

        $sql = "SELECT * FROM days ORDER BY idDays";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            // output data of each row
            while($row = $result->fetch_assoc()) {
                //do  anything
            }
        } else {
            echo "0 results";
        }