将电子邮件插入数据库

时间:2015-07-24 01:35:19

标签: php mysqli

尝试在数据库中构建电子邮件列表。我制作了这段代码,但它没有用,而且我没有收到任何错误。我是在正确的轨道上吗?

HTML:

<div id="signup">
 <h1>Sign-Up For Our Newsletter!</h1>
 <form method="post" action="scripts/php/addSubscription.php">
  <label for="email">E-mail: </label><input type="email" name="email" size="75"> <input type="submit">
 </form>
</div>

PHP:

require('settings/globalVariables.php');
require('settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ($email)";
if (mysqli_query($conn, $sql)) {
  echo 'You have successfully subscribed!';
}
else {
 echo 'Sorry, An error occured. Please try again.';
 }
mysqli_close($conn);

$conn是mysqli_connect.php

中的变量

添加mysqli_connect.php的内容仅供参考:

<?php
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
?>

我在几个数据库上使用它,每次都连接。

编辑:

每个答案/评论更新了代码,但仍然没有发生任何事情。

require('settings/globalVariables.php');
require('settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";
if (mysqli_query($conn, $sql)) {
  echo 'You have successfully subscribed!';
}
else {
 echo "Error: ".mysqli_error($conn);
 }
mysqli_close($conn);

解决:

require('/home/jollyrogerpcs/public_html/settings/globalVariables.php');
require('/home/jollyrogerpcs/public_html/settings/mysqli_connect.php');
mysqli_select_db($conn,"newsletterlist");
$email = mysqli_real_escape_string($conn, $_POST['email']);
$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";
if (mysqli_query($conn, $sql)) {
  echo 'You have successfully subscribed!';
}
else {
 echo "Error: ".mysqli_error($conn);
 }
mysqli_close($conn);

1 个答案:

答案 0 :(得分:1)

您目前收到错误,但您的代码并未向您显示。打印错误开始:

if (mysqli_query($conn, $sql)) {
  echo 'You have successfully subscribed!';
}
else {
    echo "Error: ".mysqli_error($conn);
}

您遇到的真正错误是语法错误。这就是生成的SQL的样子:

INSERT INTO newsletterusers (email) VALUES (hello@email.com)

请注意,周围没有引号,您可以使用引号括住$email来修复它:

$sql = "INSERT INTO newsletterusers (email) VALUES ('$email')";