我使用托管公司aPlus.net,我似乎无法解决我在尝试处理某些php将数据库内容写入网页时遇到的连接错误,我很好奇至于是否这是因为我的数据库似乎与我的主机帐户的其余部分不在同一台服务器上,并且是否有办法在我的代码中解决这个问题?这是我编写PHP的第一次尝试,很高兴知道我的代码是错误的,还是我的托管公司搞砸了我。 (无论哪种方式,如何修复它)
以下是未能从数据库中提取的代码:
{
$con = mysql_connect("localhost","2p5dq9vxmy240651","MY_PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("felineasthma_2p5dq9vxmy240651", $con);
$users_name = $_POST['name'];
$users_comment = $_POST['requests'];
$users_name = mysql_real_escape_string($users_name);
$users_comment = mysql_real_escape_string($users_comment);
$inputid = $_GET['id'];
$query = "
INSERT INTO `felineasthma_2p5dq9vxmy240651`.`submissions` (`id`,
`name`, `requests`, `inputid`) VALUES (NULL,
'$users_name', '$users_comment', '$inputid');";
mysql_query($query);
echo "<h2>Your request has been processed, reload page.</h2>";
mysql_close($con);
}
此处有一些屏幕截图来自我的托管帐户(链接,因为我还没有足够的帖子来上传图片,抱歉):
felineasthma_2p5dq9vxmy240651 doesn't appear in my hosting account
yet it clearly exists in MySQL Manager, but on a different server
在为这个数据库创建用户时我更加困惑,因为控制面板不允许我创建用户名,它只是随机分配一个。救命?建议?
答案 0 :(得分:0)
我找到了一个更现代的学习PHP的教程,现在一切正常,我现在只需要添加安全措施。这是工作代码片段,如果有人来这里问同样的问题。
这里是将条目放入数据库的表单操作:
<?php
$servername = "sql5c40n.carrierzone.com";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
$users_name = $_POST['name'];
$users_request = $_POST['requests'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO submissions (name, requests)
VALUES ('$users_name', '$users_request')";
if (mysqli_query($conn, $sql)) {
header("Location: clv.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
这里是将数据库条目放到页面上的include:
<?php
$servername = "sql5c40n.carrierzone.com";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, requests, name FROM submissions";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "" . $row["requests"]. " - by " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>