0

Notice: Undefined variable: title in E:\xampp\htdocs\blog4\new-post.php on line 11

I keep getting this error and also Missing data is appearing before any data is submitted

include('db.php');

        if(isset($_POST['submit'])){
        $title = $_POST['title'];
        $body = $_POST['body'];

}

if($title && $body){
            $query = mysql_query("INSERT INTO posts (title, body) VALUES('$title', '$body')");
            if($query){
                echo"Post Added";
                }else{
                echo"error";}
        }else{
            echo"Missing data";
        }
4

5 回答 5

1

db.php

<?php
$db = new PDO('mysql:host=127.0.0.1;dbname=db_name_here', 'username', 'password');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>

new-post.php

<?php
include 'db.php';
if(isset($_POST['submit'])) {
    $query = $db->prepare('INSERT INTO posts (title, body) VALUES (?, ?)');
    $result = $query->execute(array($_POST['title'], $_POST['body']));
    if($result) {
        echo 'Post Added!';
    } else {
        echo 'Database error.';
    }
} else {
    echo 'Missing data!';
}
?>

不要使用mysql_*函数,它们不再被维护并且处于弃用过程中。

请改用PDO

PDO 还支持预处理语句,这有助于避免 SQL 注入。

于 2012-11-12T00:24:00.890 回答
1

如果$_POST['submit']没有设置,$title将不会被初始化。

于 2012-11-12T00:01:24.573 回答
1

替换为

if (isset($title, $body)) {
    //....
于 2012-11-12T00:02:22.053 回答
0

Check for a POST request then check and set your values; If values are not null then do your query, also make your inputs safe else having ' in your data will cause an error.

include('db.php');

if($_SERVER['REQUEST_METHOD']=='POST'){
    $title = (!empty($_POST['title'])?$_POST['title']:null);
    $body  = (!empty($_POST['body'])?$_POST['body']:null);

    if($title != null && $body != null){
        $query = mysql_query("INSERT INTO posts (title, body) VALUES ('".mysql_real_escape_string($title)."', '".mysql_real_escape_string($body)."')");
        if($query){
            $result = "Post Added";
        }else{
            $result = "Error";
        }
    }else{
        $result = "Missing data";
    }

    echo $result;
}
于 2012-11-12T00:12:42.497 回答
0

像这样在顶部用空初始化 $title

$title = "";
于 2012-11-12T00:02:38.347 回答