2013-12-09 155 views
-1

我有一个名为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文件?

回答

2

这是一个variable scope的问题。

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,但通常被认为是一种不好的做法,应该避免:$connection除非你把它作为一个参数不提供给add_post()

+0

感谢您的意见,它有道理。现在我得到以下错误: **可捕获的致命错误:类mysqli的对象无法转换为/Applications/MAMP/htdocs/blog/includes/functions.php第7行中的字符串** –

+0

请参阅下面Marc的回答对于该解决方案 –

+0

谢谢约翰。我解决了这个问题,现在它只是在我提交表单时显示为一个空白页面,并且不会插入任何记录。 –

6

这是完全错误的:

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

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

+0

现在也是这样。它作为一个字符串传递。现在它只是在删除引号后显示空白页面 –

1

上面的答案应该让它为你工作,但考虑使用mysqli准备语句,而不是mysqli_query。准备好的语句更安全,并通过用户输入来防止sql注入。

+0

这是正确的。我只想把事情放在第一位,然后再次回过头来探讨安全问题。我知道这就像用右手抓住左耳朵,但是这对我来说更有意义。 –

+0

够公平,只要确定;) –