2013-12-09 208 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

夠公平,只要確定;) –