我有一个名为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的回答对于该解决方案 –
谢谢约翰。我解决了这个问题,现在它只是在我提交表单时显示为一个空白页面,并且不会插入任何记录。 –