我有一个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表单保存到多个数据库,或者如何自动将数据从一个数据库复制到另一个数据库
基础教程推荐
猜你喜欢
- vue开发之生命周期 2023-10-08
- 小程序实现Token生成与验证 2023-08-11
- 微信小程序访问mysql数据库流程详解 2022-08-31
- uni-app如何实现点击按钮全屏播放视频 2023-08-29
- vue中定义全局声明vscode插件提示找不到问题解决 2023-07-09
- 利用promise及参数解构封装ajax请求的方法 2023-02-23
- 通过Ajax两种方式讲解Struts2接收数组表单的方法 2022-10-17
- React中完整实例讲解Recoil状态管理库的使用 2023-07-10
- javascript内嵌式与外链式的基本应用方式 2023-08-08
- Ajax的使用四大步骤 2023-01-20