得到错误"没有选择数据库"

时间:2015-02-11 00:32:04

标签: php mysql sql pdo

尝试查询数据库表。我在运行连接脚本时获得了连接成功的结果,但无法弄清楚查询的错误。对不起,我是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; ?>

?>

1 个答案:

答案 0 :(得分:1)

不,不要混合它们,只需要一直使用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>