大家好,这是我的PHP联系表格。它成功连接,因为我在各个点运行一些测试,看看它是否有效,但它似乎没有提交到数据库。任何人都可以帮助我吗?
<?php
define('DB_NAME', 'x');
define('DB_USER', 'x');
define('DB_PASSWORD', 'x');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use' . DB_NAME . ': ' . mysql_error());
}
$value = $_POST['UserName'];
$value1 = $_POST['UserEmail'];
$value2 = $_POST['UserMessage'];
$sql = "INSERT INTO ContactUs (UserName, UserEmail, UserMessage) VALUES ('$value', '$value1', '$value2')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
我还附上了联系表单的实际代码片段(在模态框中):
<div class = "modal fade" id = "contact" role="dialog">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<h4>Contact form</h4>
</div>
<div class = "modal-body">
<p>HELLO HELLO HELLO HELLO</p>
</div>
<div class="form-group">
<form action="ContactUs.php" method="post">
<div class="form-group">
<label for="UserEmail">Email address</label>
<input type="text" class="form-control" id="UserEmail" name="UserEmail" placeholder="What is your E-Mail">
</div>
<div class="form-group">
<label for="UserName">Name</label>
<input type="text" class="form-control" id="UserName" name="UserName" placeholder="What is your name?">
</div>
<div class="form-group">
<label for="UserMessage">Message</label>
<input type="text" class="form-control" id="UserMessage" name="UserMessage" placeholder="What would you like to say?">
</div>
<input type="Submit" value="Submit" class="btn btn-default">Submit</button>
</form>
</div>
<div class = "modal-footer">
<a class = "btn btn-default" data-dismiss = "modal">Close</a>
<a class = "btn btn-primary" data-dismiss = "modal">Close</a>
</div>
</div>
</div>
</div>
</div>
看看这是一个联系表格我只是希望将信息发送到我的电子邮件,如果有人能告诉我这是否合适,那将是很好的[如果它不是如何调整它以使其如此]。我使用了视频教程[下面的链接],但他只提到了如何存储到数据库中。
答案 0 :(得分:0)
您在检查if (!link)
时遇到了拼写错误,但此外,您应该使用更新,更安全的MySQLi
功能。试试这个:
<?php
define('DB_NAME', 'x');
define('DB_USER', 'x');
define('DB_PASSWORD', 'x');
define('DB_HOST', 'localhost');
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_errno)
{
die("Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error);
}
$userName = $_POST['UserName'];
$userEmail = $_POST['UserEmail'];
$userMessage = $_POST['UserMessage'];
if (!($stmt = $mysqli->prepare("INSERT INTO ContactUs (UserName, UserEmail, UserMessage) VALUES (?, ?, ?)")))
{
die("Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error);
}
$stmt->bind_param("sss", $userName, $userEmail, $userMessage);
if (!$stmt->execute())
{
die("INSERT failed: (" . $stmt->errno . ") " . $stmt->error);
}
$mysqli->close();
这使用Prepared Statements,出于所有意图和目的,它将预准备语句定义中的?
标记替换为绑定到语句的变量的转义值。这有助于防止SQL注入。