php'没有选择数据库'但它连接到数据库

时间:2015-09-11 15:30:49

标签: php mysql

我已经检查过具有相同标题的其他问题,但无法解决此问题。我已连接到数据库,因为登录工作正常,我可以显示用户的用户名。这是相关代码,第二部分是造成错误的原因,谢谢:

<?php require 'connection.php' ?>
<?php
session_start();
?>


<content>
                <?php
                //Select all from the categories table and order by the  category title in ascending order (ASC)
                $sql = "SELECT * FROM categories ORDER BY category_title ASC";

                //$res = the result of the above query or die if error
                $res = mysql_query($sql) or die (mysql_error());

                if (mysql_num_rows($res) > 0) {

                } else {
                    "<p>No categories availible</p>";
                }


                ?>

                </content>

1 个答案:

答案 0 :(得分:2)

这是一个例子,为了它的视觉效果。

<?php
    $dbname = 'so_gibberish';
    $dbuser = 'GuySmiley';
    $dbpass = 'MyPassword';
    $dbhost = 'localhost';
    $link = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
    mysql_select_db($dbname) or die("Could not open the db '$dbname'");

    $test_query = "SHOW TABLES FROM $dbname";
    $result = mysql_query($test_query);
    ...
    ...
    mysql_close($link);

但是,请使用PDO

它不那么恶心,充满了健壮性,并且至少可以说更具安全性:

再次,只是一个视觉。

<?php
    $theNum=102;    // get from user, this is hard-coded
    try {
        $dbh = new PDO('mysql:host=localhost;dbname=so_gibberish;charset=utf8', 'GuySmiley', 'MyPassword');
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $dbh->prepare('SELECT id,smin,smax from ranges7 
            WHERE smin <= :theNum AND smax >= :theNum');
        $stmt->bindParam(':theNum', $theNum, PDO::PARAM_INT);
        $stmt->execute();
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            // one row we hope
            $data = "id: ".$row['id'] . ", smin: " . $row['smin'] . ", smax: " . $row['smax'] . "\n";
            print $data;
        }
        $stmt = null;
        // PDO closes connection at end of script

    } catch (PDOException $e) {
        echo 'PDO Exception: ' . $e->getMessage();
        exit();
    }
?>