PHP mysqli没有woking

时间:2017-02-16 16:19:07

标签: php mysqli

Pic

所以我是mysqli的新手。我在网上找到的所有例子似乎都是旧的(程序性的)做事方式。有人能告诉我为什么我的代码不能在下面工作吗?我的数据库是'templatedb'。我的表是'模板'。我的表中有一个条目,但我的回声没有输出。我的代码没有任何错误。

        <div id="templateSelector">  
        <?php
        $hostname = "localhost";
        $username = "root";
        $password = "";
        $db = "templatedb";
        //connect
        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        $database = mysqli_connect($hostname, $username, $password, $db);
        if(!$database){
            die("Could not connect to the database");                
        }

        if ($database->connect_errno) {
            echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
        } else {
            $sql = "SELECT * FROM template";
            if (!$result = $database->query($sql)) {
                die('There was an error running the query [' . $db->error . ']');
            } else {

                echo "<label>Select Template</label>";
                echo "<select name='templates'>";
                while ($row = $result->fetch_assoc()) {
                    echo "hello";
                    echo $row['template_name'];
                    // echo "<option value='" . $row['template'] . "'>" . $row['template'] . "</option>";
                }
                echo "</select>";
            }
        }
        ?>

1 个答案:

答案 0 :(得分:-2)

尝试执行以下操作,为我工作

<div id="templateSelector">  
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$db = "templatedb";
$mysqli = mysqli_connect($hostname, $username, $password, $db);
if($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
} else {
    $sql = "SELECT * FROM template";
    $result = mysqli_query($mysqli, $sql);
    if(!$result = $mysqli->query($sql)) {
        die('There was an error running the query [' . $db->error . ']');
    } else {
        echo "<label>Select Template</label>\n";
        echo "<select name='templates'>\n";
        while($row = $result->fetch_assoc()) {
            echo "<option>id = " . $row['id'] . "</option>\n";
        }
        echo "</select>";
    }
}
?>
</div>

enter image description here

确保您的DATABASE被称为templatedb,其所在的表名为template,并且有一行名为id。我知道这听起来微不足道,但拼写错误会破坏你的代码。