繁体   English   中英

将表单数据引用到php脚本并将其插入数据库

[英]Referencing form data to php script and inserting it into database

好吧,我到处都是。 首先,我有一个表单,一个时事通讯,用户可以在其中输入电子邮件。 一旦他们点击了提交,它将检查一个php表单,该表单接收该电子邮件并将其输入到存储该电子邮件的SQL数据库中。 问题是提交表单时出现此错误

Error: INSERT INTO emails (email) VALUES (random@yahoo.com) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@yahoo.com)' at line 2

不知道为什么它不会将其放入数据库。 表单代码是

 <section>
            <div class="mockup-content">
                <div class="morph-button morph-button-inflow morph-button-inflow-1">
                    <button type="button"><span>Subscribe to our Newsletter</span></button>
                    <div class="morph-content">
                        <div>
                            <div class="content-style-form content-style-form-4">
                                <h2 class="morph-clone">Subscribe to our Newsletter</h2>
                                <form action="scripts/mailer.php" method="post">
                                    <p><input type="text" class="button" id="email" name="email" placeholder="NAME@EXAMPLE.COM">
                                    <div>We promise, we won't send you any spam. Just love.</div>
    <input type="submit" class="button" id="submit" value="SIGN UP"></p>
                                </form>
                            </div>
                        </div>
                    </div>
                </div><!-- morph-button -->
            </div>
        </section>

这只是表单的html数据,php数据是

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mysql";
$email = ($_POST["email"]);


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

 $sql = "INSERT INTO emails (email)
  VALUES ($email)";

if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
 } else {
   echo "Error: " . $sql . "<br>" . $conn->error;
 }

$conn->close();
?>

谁能解释为什么?

在查询中绑定变量时,应使用打勾( ' ):

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

当您要绑定的变量的值是int时,最好不要使用tick。

电子邮件为varchar数据类型。 你需要在上面加引号

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM