我已经连续进行了三天的工作,我开始失去理智了……我需要做的是将数据库连接到html表单,以便它添加新信息。通过使用PHP(这是困扰我的噩梦)来完成所有这些工作。
$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'root';
$db_name = 'grnh';
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = 'SELECT *
FROM contact';
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<form method="POST">
<!-- Name -->
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name"><br>
<!-- Email -->
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" placeholder="example@gmail.com">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<!-- Message -->
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" id="message" rows="4"></textarea>
</div>
</div>
<!-- Button -->
<button type="submit" class="btn btn-dark">Submit</button>
</form>
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$sql = "INSERT INTO contact(name, email, message)
VALUES('$name', '$email', '$message');";
$result = mysqli_query($conn, $sql);
?>
到目前为止,我已经设法连接数据库(我认为...),但是每当我填写表单时,它并没有添加新信息,而是在数据库中添加了两个空格... 我不知道这是否重要,但是我正在使用MAMP(myPHP Admin)...