2013-04-02 43 views
0

謝謝你們,算出來,原來它是在js一個詞是拼寫不正確,總有一些簡單的PHP沒有寫入第一場SQL

這是我的腳本將數據寫入到我的數據庫在我的本地服務器上,它目前只寫入2個字段,而不是別名,我做錯了什麼?我已經三重檢查了html表單和數據庫字段中的名稱。

<?php 
    // 1. Create connection to database 

    mysql_connect('localhost','root','') or die('Could not connect to mysql: <hr>'.mysql_error()); 

    // 2. Select database 

    mysql_select_db("trialdb") or die('Could not connect to database:<hr>'.mysql_error()); 

    // 3. Assign variables (after connection as required by escape string) 

$alias = $_POST['alias']; 
$name = $_POST['name']; 
$email = $_POST['email']; 

    // 4. Insert data into table 

    mysql_query("INSERT INTO user_data (alias, name, email) VALUES ('$alias', '$name', '$email')"); 
    Echo 'Your information has been successfully added to the database.'; 
    print_r($_POST); 
    mysql_close() 
?> 
+1

你檢查是否'$ _ POST []'變量返回值 –

+0

1;不要使用'mysql_query'。 2;當然,不要將'$ _POST'逐字地注入到查詢中。 3;你有沒有試過迴應它將要運行的查詢?看到你在'$ _POST'中實際上有值,並且讓你有機會直接在DB上執行。 –

+1

print_r($ _ POST)的輸出給你什麼? – shannonman

回答

0

,首先你應該總是檢查POST變量都被正確發送:

if (
    !isset($_POST['alias']) or 
    !isset($_POST['name']) or 
    !isset($_POST['email']) 
) // something is wrong 

其次,你不想直接截獲用戶輸入的SQL查詢。您應該執行的第一部分逸出(甚至更好PDOmysqli更換mysql_*過時的驅動程序,只需使用prepared statements):

$alias = mysql_real_escape_string($_POST['alias']); 
$name = mysql_real_escape_string($_POST['name']); 
$email = mysql_real_escape_string($_POST['email']); 

第三,你如果查詢打印成功的消息之前進行正確要檢查:

$res = mysql_query("INSERT INTO user_data (alias, name, email) VALUES ('$alias', '$name', '$email')"); 

echo ($res) 
    ? 'Your information has been successfully added to the database.' 
    : 'Your information couldn't be added to the database'; 
0

你可以嘗試

<?php 

$conn = mysql_connect('localhost','root','') or die('Could not connect to mysql: '.mysql_error()); 

mysql_select_db("trialdb", $conn) or die('Could not connect to database:'.mysql_error()); 

$alias = $_POST['alias']; 
$name = $_POST['name']; 
$email = $_POST['email']; 

mysql_query("INSERT INTO user_data (`alias`, `name`, `email`) VALUES ('$alias', '$name', '$email')", $conn); 

echo 'Your information has been successfully added to the database.'; 

print_r($_POST); 

mysql_close(); 

?>