我的数据没有存储在我的数据库中

时间:2015-05-07 20:40:16

标签: php

我似乎无法弄清楚我的代码有什么问题。我试图让它从

获取输入
<form id="contact-form" action="emails.php" method="post">
    <input placeholder="Please enter your email address" name="emailz" type="email" tabindex="2" required>
    <input type="submit" name="submit" id="contact-submit" value="Subscribe">
</form>

并将其保存到我的数据库中。

这是我的PHP文件:

$servername = "localhost";
$username = "poweilup";
$password = "bloop";
$dbname = "poweilup_emails";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$insert = "INSERT INTO emails(addressEmail) VALUES($_POST '$emailz')";
$conn->close();

3 个答案:

答案 0 :(得分:1)

以下是插入方式 -

$servername = "localhost";
$username = "poweilup";
$password = "bloop";
$dbname = "poweilup_emails";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$stmt = $conn->prepare("INSERT INTO `emails`(`addressEmail`) VALUES(?)");
$stmt->bind_param('s', $email);

$email = $_POST('emailz');
$stmt->execute();

首先准备查询并为项变量保留占位符。你bind each parameter(variable)然后声明它们。最后执行查询。

答案 1 :(得分:1)

要以安全的方式使用MySQLi,最好使用Prepared Statements。这将阻止您的用户插入SQL注入,或者可能错误地插入可能导致MySQL服务器出现问题的字符。

正如您在下面的脚本中看到的,我首先使用占位符&#34;?&#34;准备SQL查询。对于项目变量。在我将参数(变量)绑定到此占位符之后。

现在查询设置正确,是时候执行了。一旦完成就关闭任何剩下的东西总是一个好习惯,因为它会释放不再使用的记忆。

<?php

/* DB Info */
$servername = "localhost";
$username = "poweilup";
$password = "bloop";
$dbname = "poweilup_emails";

/* MySQLi Object */
$conn = new mysqli($servername, $username, $password, $dbname);

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Prepare query */
if ($stmt = $conn->prepare("INSERT INTO emails (addressEmail) VALUES (?)")){

    /* Bind POST data */
    $stmt->bind_param("s", $_POST['emailz']);

    /* Run query */
    $stmt->execute();

    /* Close statement */
    $stmt->close();
}

/* Close connection */
$conn->close();

?>

答案 2 :(得分:-1)

首先检查用户是否遗漏了任何内容:

if (isset($_POST['emailz']) { //code here.. };

code here...部分中,将emailz的值存储在如下变量中:

$emailz = $_POST['emailz'];

当然,对于像密码这样的更重要的数据,这可能是不安全的。您应该使用hash()函数。

要在DB中插入变量,请尝试以下操作:

$query = "INSERT INTO `user` (emailz) VALUES ('$emailz')"; $result = mysql_query($query);     //inserts the variable in the DB.