溫馨提示×

html怎么連接mysql數(shù)據(jù)庫

小億
81
2024-09-29 02:56:50
欄目: 云計算

在HTML中,您不能直接連接到MySQL數(shù)據(jù)庫。您需要使用服務器端腳本(如PHP、Python、Node.js等)來與數(shù)據(jù)庫進行交互。以下是使用PHP連接MySQL數(shù)據(jù)庫的示例:

  1. 首先,確保您的服務器已安裝PHP和MySQL。

  2. 創(chuàng)建一個名為config.php的文件,用于存儲數(shù)據(jù)庫連接信息:

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

// 創(chuàng)建連接
$conn = new mysqli($servername, $username, $password, $dbname);

// 檢查連接
if ($conn->connect_error) {
    die("連接失敗: " . $conn->connect_error);
}
echo "連接成功";
?>
  1. 在HTML文件中,使用<script>標簽調用config.php文件,并通過AJAX獲取數(shù)據(jù)庫數(shù)據(jù):
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>連接MySQL數(shù)據(jù)庫示例</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>連接MySQL數(shù)據(jù)庫示例</h1>
    <div id="result"></div>

    <script>
        $(document).ready(function() {
            $.ajax({
                url: 'config.php',
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    if (data.connect_success) {
                        $.ajax({
                            url: 'get_data.php',
                            type: 'GET',
                            dataType: 'json',
                            success: function(data) {
                                var result = '';
                                for (var i = 0; i < data.length; i++) {
                                    result += '<p>' + data[i].column_name + ': ' + data[i].value + '</p>';
                                }
                                $('#result').html(result);
                            }
                        });
                    } else {
                        $('#result').html('<p>連接失敗: ' + data.connect_error + '</p>');
                    }
                }
            });
        });
    </script>
</body>
</html>
  1. 創(chuàng)建一個名為get_data.php的文件,用于從數(shù)據(jù)庫中獲取數(shù)據(jù):
<?php
// 引入config.php文件
require_once 'config.php';

// 查詢數(shù)據(jù)
$sql = "SELECT column_name, value FROM your_table_name";
$result = $conn->query($sql);

$data = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
} else {
    echo json_encode(array('error' => '沒有查詢到數(shù)據(jù)'));
}

// 設置響應頭為JSON格式
header('Content-Type: application/json');
echo json_encode($data);

// 關閉數(shù)據(jù)庫連接
$conn->close();
?>

請注意,您需要根據(jù)實際情況修改config.php、get_data.php和HTML文件中的數(shù)據(jù)庫連接信息、表名和列名。

0