我是一名计算机科学专业的学生,大二。为了独立学习,我决定创建一个使用 SQL、PHP、JS、AJAX、BOOTSTRAP 等技术的网站。我正在尝试向数据库添加内容,我使用 AJAX - 我不想刷新页面,所以我使用 AJAX。我设法将内容添加到数据库 - 但页面刷新。我尝试使用 jquery - 当我添加内容时 - 来防止刷新。该代码有效 - 但仍然需要刷新。
访问数据库的代码:
<?php
$DBConInfo = [
'server' => '127.0.0.1',
'username' => 'root',
'password' => '',
'name' => 'test',
];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($DBConInfo['server'],$DBConInfo['username'], $DBConInfo['password'],$DBConInfo['name']);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// php code to Insert data into mysql database from input text
if(isset($_POST['insert']))
{
$hostname = "127.0.0.1";
$username = "root";
$password = "";
$databaseName = "test";
// get values form input text and number
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
$picture = $_POST['picture'];
// mysql query to insert data
$query = "INSERT INTO `product`(`name`,`description`, `price`, `picture`) VALUES ('$name','$description','$price','$picture')";
$result = mysqli_query($conn,$query);
// check if mysql query successful
if($result) {
echo 'Data Inserted';
}
else{
echo 'Data Not Inserted';
var_dump($conn->error);
}
//mysqli_free_result($result);
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<head>
<title> PHP INSERT DATA </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
慕的地10843