使用PHP

时间:2018-12-03 19:48:48

标签: php mysql

我有一个应该使用用户输入执行插入语句的网页,我相信我已经正确设置了所有内容,但是运行脚本时表未更改,并且没有收到错误消息。我认为这里的语法可能存在问题:

    "INSERT INTO student (FirstMidName,lastname) VALUES ('{$conn- 
   >real_escape_string($_POST['FirstMidName'])} ,
     {$conn->real_escape_string($_POST['lastname'])}')";

以下是完整的代码供参考:

<?php

if ($_SERVER["REQUEST_METHOD"]=="POST"){
$host = "localhost";
$db = "cis475";
$user = "root";
$pw = "";




$conn = new mysqli ($host, $user, $pw, $db);
if($conn){echo "Connection established <br>";}
if($conn->connect_error) die($conn->connect_error);

$sql = "INSERT INTO student (FirstMidName,lastname) VALUES ('{$conn->real_escape_string($_POST['FirstMidName'])} , {$conn->real_escape_string($_POST['lastname'])}')";
$insert = $conn->query($sql);

$conn->close();

}
?>

<html>

<form method="post" action="">
    First Name:<input name="FirstMidName" type="text">
    Last Name:<input name="lastname" type="text">
    <input type="submit" value="Submit Form">
</form>

</html>

1 个答案:

答案 0 :(得分:0)

如果没有正确输出,将很难找到导致错误的原因。我会尝试清理您的Sql查询并输出错误。尝试将您的php脚本更改为此:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $host = "localhost";
    $db = "cis475";
    $user = "root";
    $pw = "";

    $conn = new mysqli ($host, $user, $pw, $db);
    if ($conn) {
        echo "Connection established <br>";
    }
    if ($conn->connect_error) {
        die($conn->connect_error);
    }

    $firstMidName = $conn->real_escape_string($_POST['FirstMidName']);
    $lastName = $conn->real_escape_string($_POST['lastname']);

    $sql = "INSERT INTO student (FirstMidName,lastname) VALUES ('$firstMidName', '$lastName')";

    if (!$conn->query($sql)) {
        echo "Error message:" + $conn->error;
    }

    $conn->close();
}