我有一个HTML表单,例如form action=form.php method=postFirst name:brinput type=text id=fname name=fnamebrLast name:brinput type=text id=lname name=lnamebrbrinput ...
我有一个HTML表单,例如
<form action="form.php" method="post">
First name:<br>
<input type="text" id="fname" name="fname">
<br>
Last name:<br>
<input type="text" id="lname" name="lname">
<br><br>
<input type="submit" value="Submit">
</form>
和form.php
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
form.php将该数据保存到database1.
我希望将这些数据与database1一起保存到另一个数据库database2中.
可能吗 ??如果是,那么应该对代码进行哪些更改?
如果不可能,是否可以将数据从数据库1自动复制到数据库2?每当在database1中添加新行时,它都应自动复制到database2.
我希望相同的数据位于两个不同的数据库中.我如何实现上述任何一项?
解决方法:
从php中,您只需要创建与数据库的新连接即可.
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
$servernameS = "localhost";
$usernameS = "database2";
$passwordS = "xxxxxxxx";
$dbnameS = "database2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$connS = new mysqli($servernameS, $usernameS, $passwordS, $dbnameS);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($connS->connect_error) {
die("Connection failed: " . $connS->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
if ($connS->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $connS->error;
}
$conn->close();
$connS->close();
?>
沃梦达教程
本文标题为:PHP SQL:如何将数据从一个html表单保存到多个数据库,或者如何自动将数据从一个数据库复制到另一个数据库
猜你喜欢
- 如何给JS中的数组开头添加元素 2022-08-30
- html中两种获取标签内的值的方法 2022-09-21
- 一篇文章让你看懂Js继承与原型链 2023-08-12
- JavaScript defineProperty如何实现属性劫持 2023-08-08
- 完美解决ajax访问遇到Session失效的问题 2023-01-20
- ajax向服务器端传值出现乱码问题 2022-11-22
- html+css实现分层金字塔的实例 2022-09-20
- vue引入html2canvas插件实现图片嵌入div展示下载 2023-10-08
- JS+CSS实现超漂亮的动态翻书效果(思路详解) 2023-07-09
- 下拉菜单的级联操作(ajax) 2023-01-21