在本地主机上使用带有xampp的PHP获取数据并将其插入MySQL数据库
我设法连接到数据库,并设法使用以下代码进行插入.
I have managed to connect to database and I manage to insert using following code.
<?php
$username = 'root';
$password = '';
$db = 'demo';
$conn = new mysqli ('localhost',$username, $password, $db) or die("unable to connect");
$sql="insert into persons (first_name,last_name,email_address) values ('sara','smith','email@email.com')";
$query=mysqli_query($conn,$sql);
if($query)
echo 'data inserted';
?>
但是问题是,当我尝试使用HTML表单输入数据时,它对我不起作用.我试图在stackoverflow上遵循不同的教程和不同的答案.谁能告诉我使用PHP从MySQL插入和获取数据的最简单方法吗?
But the problem is that when I try to enter data using HTML form, it didn't work for me. I have tried to follow different tutorials and different answers here on stackoverflow. Can anyone please tell me the easiest way of inserting and getting data from MySQL using PHP ?
如果有任何简单的教程或博客可以让我学习和理解所有这些内容,我很乐意观看或阅读.
If there is any easy tutorial or blog from where i can learn and understand all this, I would love to watch or read.
我设法按照以下方式进行操作.
I manage to do it in following way.
使用以下代码创建文件名index.php
Create a file name index.php with following code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="firstname" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
然后创建另一个文件名为insert.php
Then create another file name as insert.php
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);
// attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>