需要将网站连接到数据库


Need to connect a website to a database

我有一个充满手机规格的数据库,我需要网站在一个已经创建的html表中显示,用户输入搜索框的手机规格。我有HTML的知识,但从来没有链接到一个数据库的网站,谁能推荐最好的方式来完成我需要什么?有什么有用的建议吗?我已经安装了XAMPP并在PHPmyadmin中创建了数据库,但以前从未使用过php,所以不知道从哪里开始。提前感谢

首先可以使用下面的代码,但要考虑学习预处理语句或PDO。

<?php
//Make the connection to your database
$connection = mysqli_connect('localhost', 'root', 'your_password', 'your_database');
mysqli_set_charset($connection, 'utf8');
if (!$connection) {
    die("Database connection failed: " . mysqli_error());
}
//Query the database
$query = "SELECT col1, col2, col3 FROM your_table;";
$result = mysqli_query($connection, $query);
if(!$result) {
    die("SQL Error: " . mysqli_error($connection));
}
?>
<table>
    <?php //Fetch all the results ?>
    <?php while ($row = mysqli_fetch_array($result)) : ?>
    <tr>
        <td><?php echo htmlspecialchars($row['col1']); ?></td>
        <td><?php echo htmlspecialchars($row['col2']); ?></td>
        <td><?php echo htmlspecialchars($row['col3']); ?></td>
    </tr>
    <?php endwhile; ?>
</table>

步骤1:创建connection.php并插入以下代码:

<?php
$dbConnection = mysqli_connect("yourHost","root", "password", "databaseName");
if(mysqli_connect_errno())
{
    echo "Failed to connect" . mysqli_connect_error();
}
?>

步骤2:当想要在另一个文件中执行MySQL时,比如,index.php,使用这个:

include_once("connection.php");
        $sql = "SELECT * FROM tableName"; // This creates the SQL Query
        $query = mysqli_query($dbConnection, $sql); // This executes it

从这里开始,它只需要知道基本的PHP,将允许你做你喜欢你的网站,但它是非常重要的,你学习PHP和一点点MySQL,祝你好运