-1

我正在尝试自学如何编写网站代码,我需要从表单中获取一些信息并将其放入我的 mysql 数据库中,而我收集到的最好的方法是使用 php。当我点击提交按钮时,我的 index.php 中的脚本会执行,但数据库中没有任何内容。该脚本链接到我的 Web 根目录之外的另一个脚本。我需要把它放在那里,因为它包含密码(有没有更好的方法来做到这一点?)这可能是我的问题的一部分。以下是相关的代码:

 <?php
 $con=mysqli_connect("192.168.1.125","root","pass","site");
 // Check connection
 if (mysqli_connect_errno())
 {
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

 $sql="INSERT INTO users (Email)
 VALUES
 ('$_POST[email]')";

 if (!mysqli_query($con,$sql))
 {
 die('Error: ' . mysqli_error($con));
 }
 echo "1 record added";

 mysqli_close($con);
 ?> 

        <?php
    // define variables and set to empty values
    $emailErr = "";
    $email = $password = "";
    $file = basename(urldecode($_GET['insert.php']));
    $fileDir = '/var/insert.php';

    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        if (empty($_POST["email"]))
            {$emailErr = "email is required";}
        else
            {$email = test_input($_POST["email"]);
            if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
                {
                $emailErr = "Invalid email format";
                }
            }
    }

    function test_input($data)
    {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }

    if (file_exists($fileDir . $file))
    {
    // Note: You should probably do some more checks 
    // on the filetype, size, etc.
    $contents = file_get_contents($fileDir . $file);

    // Note: You should probably implement some kind 
    // of check on filetype
    header('Content-type: php');

    echo $contents;
    }
    ?>
        <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
        <input id="email" placeholder=" email" type="email" name="email" maxlength="50">
        <input id="pass" placeholder=" Password" type="password" name="pass" maxlength="25">
        <button id="submit">SUBMIT</button></form>
    </div>
    </div><div id="date" align="center"><img src="192.168.1.125/date.png"></div>
    <?php
    echo "<h2>Your Input:</h2>";
    echo "$email";
    echo "$emailErr";
    ?>
4

2 回答 2

1

换行,

  $sql="INSERT INTO users (Email) VALUES ('$_POST[email]')";

  $sql="INSERT INTO users (Email) VALUES ('".$_POST['email']."')";
于 2013-10-10T17:00:20.880 回答
0
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql="INSERT INTO users (Email)
 VALUES
 ('$email')";
于 2013-10-10T17:01:36.777 回答