Pop*_*rei -1 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();
}
?>
Run Code Online (Sandbox Code Playgroud)
我有一个名为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)";
}
?>
Run Code Online (Sandbox Code Playgroud)
和一个插入帖子的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");
}
?>
Run Code Online (Sandbox Code Playgroud)
当我尝试发布一些文本时,我收到以下错误:
注意:未定义的变量:第7行的/Applications/MAMP/htdocs/blog/includes/functions.php中的连接
我在这做错了什么?不是$连接应该传递,因为我使用require(); 在我的newPost.php文件中?
这是完全错误的:
$insert_post = "mysqli_query($connection, $post)";
^--- ^--
Run Code Online (Sandbox Code Playgroud)
您没有执行查询.您正在定义一个字符串,该字符串恰好包含一些看起来像查询调用的文本.删除引号......