我有一個名爲database.php中包含以下內容:Php/MySQL插入記錄查詢錯誤?
<?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");
}
?>
當我嘗試發佈一些文字,我得到以下錯誤:
注意:未定義的變量:連接在/Applications/MAMP/htdocs/blog/includes/functions.php第7行
我在這裏做錯了什麼?不是$連接應該被傳遞,因爲我使用require();在我的newPost.php文件?
感謝您的意見,它有道理。現在我得到以下錯誤: **可捕獲的致命錯誤:類mysqli的對象無法轉換爲/Applications/MAMP/htdocs/blog/includes/functions.php第7行中的字符串** –
請參閱下面Marc的回答對於該解決方案 –
謝謝約翰。我解決了這個問題,現在它只是在我提交表單時顯示爲一個空白頁面,並且不會插入任何記錄。 –