Php / MySQL插入记录查询错误?

时间:2013-12-09 14:45:39

标签: php mysql function insert

我有一个名为database.php的文件,其中包含以下内容:

    <?php

// Database connectivity stuff

$host     = "localhost"; // Hostname for the database. Usually localhost
$username = "root"; // Username used to connect to the database
$password = "root"; // Password for the username used to connect to the database
$database = "blog"; // The database used

// Connect to the database using mysqli_connect
$connection = mysqli_connect($host, $username, $password, $database);

// Check the connection for errors
    if (mysqli_connect_errno($connection)) {
    // Stop the whole page from loading if errors occur
    die("<br />Could not connect to the database. Please check the settings and try again.") . mysqli_connect_error() . mysqli_connect_errno();
}


?>

我有一个名为functions.php的新文件,其中包含以下内容:

<?php

// Functions file for the system

function add_post($user_id, $body) {
    $post = "INSERT INTO posts (user_id, body, stamp) VALUES ($user_id, $body, now())";
    $insert_post = "mysqli_query($connection, $post)";
}

?>

一个插入帖子的php页面(newPost.php),其中包含以下内容:

<?php

// Define the user id and get the post from the form
$user_id = 1; // User ID hard coded for testing purposes
$body = substr($_POST['body'],0,200);

// Insert the post in the database using the add_post() function

if (isset($user_id, $body) && ($_SERVER['REQUEST_METHOD'] == 'POST')) {

    // Insert the post in the database if conditions were met
    add_post($user_id, $body);
    }
    // If the conditions were not met, display an error
    else {
        die("The post was not added. Something went wrong. Please try again later");
    }
?>

当我尝试发布一些文本时,我收到以下错误:

注意:未定义的变量:第7行/Applications/MAMP/htdocs/blog/includes/functions.php中的连接

我在这里做错了什么?不是$连接应该传递,因为我使用require();在我的newPost.php文件中?

3 个答案:

答案 0 :(得分:6)

这是完全错误的:

$insert_post = "mysqli_query($connection, $post)";
               ^---                             ^--

您没有执行查询。您正在定义一个字符串,该字符串恰好包含一些 LOOKS 的文本,就像查询调用一样。删除引号......

答案 1 :(得分:2)

这是一个variable scope问题。 $connection无法使用add_post(),除非您将其作为参数传递:

function add_post($user_id, $body, $connection) {
    $post = "INSERT INTO posts (user_id, body, stamp) VALUES ($user_id, $body, now())";
    $insert_post = mysqli_query($connection, $post);
}

您也可以使用global关键字,但这通常被视为不良做法,应该避免使用。

答案 2 :(得分:1)

以上答案应该让它适合你,但考虑使用mysqli预处理语句而不是mysqli_query。准备好的语句更安全,并通过用户输入保护您免受SQL注入。