获取错误 "No database selected"

Getting error "No database selected"

正在尝试查询数据库 table。当我 运行 连接脚本但无法弄清楚查询有什么问题时,我得到了连接成功的结果。抱歉,我是 php

的新手
    <?php
$servername = "localhost";
$database = "laravel";
$username = "root";
$password = "root";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }

$result = mysql_query("SELECT * FROM users WHERE id=1") or die(mysql_error());

if(mysql_num_rows($result) > 0): ?>
<table>
    <tr>
        <th>name</th>
        <th>lastname</th>
    <tr>

    <?php while($row = mysql_fetch_assoc($result)): ?>
    <tr>
        <td><?php echo $row['name']; ?></td>
        <td><?php echo $row['lastname']; ?></td>
    </tr>
    <?php endwhile; ?>

</table>
<?php endif; ?>

?>

不,不要混合使用它们,只是一直使用 PDO。相应地使用方法 ->query()->fetch()

<?php

$servername = "localhost";
$database = "laravel";
$username = "root";
$password = "root";

try {

    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the PDO error mode to exception

} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

$query = $conn->query('SELECT * FROM users');

?>

<table>
    <tr>
        <th>name</th>
        <th>lastname</th>
    <tr>

    <?php while($row = $query->fetch(PDO::FETCH_ASSOC)): ?>
    <tr>
        <td><?php echo $row['name']; ?></td>
        <td><?php echo $row['lastname']; ?></td>
    </tr>
    <?php endwhile; ?>
</table>