您好,任何可以提供帮助(或遇到相同问题)的人。
我的网站上有一个表单,我需要将数据存储在数据库中。 我在使用任何其他数据库服务时都没有问题,但在使用 Amazon RDS 数据库时就没那么幸运了。
这个php文件用于将数据发送到数据库。
<?php
$dbhost = "xxxx.xxxx.ap-southeast-2.rds.amazonaws.com";
$dbuser = "username";
$dbpass = "pasword";
$userid = $_GET['UniqueID'];
$username = $_GET['name'];
$useremail = $_GET['email'];
$userphone = $_GET['phone'];
$userref = $_GET['refid'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "INSERT INTO landing_post (`useid`, `name`, `email`, `phone`, `refid`) VALUES ('$userid', '$username', '$useremail', '$userphone', '$userref')";
mysql_select_db('bunker');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
将表单提交到原始发布操作后,它会打开以下网址。
https://example.com.au/test/post.php?&UniqueID=10020&name=burger&email=test%40mvmedia.com&phone=1800+000+000&refid=28383
$_GET 函数使用 url 中的变量填写数据。
当从基于 cpanel 的服务器运行 php 时,我收到此错误。
Could not connect: Can't connect to MySQL server on 'xxxxx.xxxxxxx.ap-southeast-2.rds.amazonaws.com' (111)
当从 AWS EC2 实例运行 php 时,我什至没有得到错误读数。
任何帮助或见解将不胜感激。 干杯, 安迪
最佳答案
向 JeanPaul98 致敬,他让我走上了正确的道路。经过多次尝试和错误,我发现下面的代码解决了这个问题。
<?php
$userid = $_GET['UniqueID'];
$username = $_GET['name'];
$useremail = $_GET['email'];
$userphone = $_GET['phone'];
$userref = $_GET['refid'];
$link = mysqli_connect('xxxxx.xxxxxx.ap-southeast-2.rds.amazonaws.com', 'User', 'password','database');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Check if server is alive
if (mysqli_ping($link))
{
echo "Connection is ok!";
}
else
{
echo "Error: ". mysqli_error($link);
}
mysqli_query($link,"INSERT INTO table (`useid`, `name`, `email`, `phone`, `refid`) VALUES ('$userid', '$username', '$useremail', '$userphone', '$userref')")
or die(mysqli_error($link));
echo "Entered data successfully\n";
mysqli_close($link);
?>
主要的变化是我停止使用 mysql 而使用 mysqli。为了使代码能够与 mysqli 一起使用,还进行了一些结构性更改。对于其他遇到类似问题的人,这里有一些需要检查的事项。
您已为 RDS 数据库安全组中的 IP 打开入站端口。
数据库可公开访问。
- 您的 php 版本已安装 PDO_MYSQL 或兼容的驱动程序(更多详细信息请参见此处 https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_PHP.rds.html )
关于php - 无法将表单数据发布到 RDS MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48198736/