2013-11-03 41 views
-1

我一直在努力研究準備好的語句,並在其中使用$ _POST變量,但是我在網上看到的東西似乎都不起作用。我知道問題是爲了展示適當的研究,但我無法在網上找到與此問題相匹配的任何內容。請告訴我我做錯了什麼。

$dbh = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass'); 
$currentdate = date("Y-m-d"); 
$key = md5(microtime().rand()); 
try { 
    $query = $dbh->prepare("INSERT INTO requests (formname, formemail, formphone, formpostcode, formitem, formnotes, formbudget, formdatefor, currentdate, deletekey, resolved, deleted) 
    VALUES (:name, :email, :phone, :postcode, :item, :notes, :budget, :datefor, :curentdate, :key, '0', '0')"); 

    $params = array_intersect_key($_POST, array('name', 'email', 'phone', 'postcode', 'item', 'notes', 'budget', 'datefor', 'currentdate', 'key')); 
    $query->execute($params); 
} 
catch (PDOException $e) { 
    error_log($e->getMessage()); 
    die("An error occurred, contact the site administrator."); 
} 
+0

您的問題中未包含錯誤消息。 –

+0

你不是隻是缺少':'在你的綁定參數? – tlenss

+0

@YourCommonSense這是因爲我沒有收到錯誤消息。 – ntzm

回答

2
$params = array_intersect_key($_POST, array('name', 'email', 'phone', 'postcode', 'item', 'notes', 'budget', 'date for', 'currentdate', 'key')); 

右側的陣列具有012$_POST陣列具有鍵nameemail等(我假設)。他們的交集是沒有的。 array_intersect_key相交,兩個數組的鍵,而不是一個鍵和另一個的值。

你想:

$params = array_intersect_key($_POST, array_flip(array('name', ...))); 
             ^^^^^^^^^^ 

這本來是很容易弄清楚,如果你曾試圖var_dump($params)

儘管沒有什麼可以保證$_POST將包含您期望的所有值,但在這種情況下您將觸發有關缺少參數的PDO錯誤,但仍然應該在此處進行錯誤檢查。

0

我相信你的$ _POST數組鍵'currentdate','key'中沒有任何地方。

+0

好的,我已經刪除了它們,稍後我會添加它們。但它仍然無法正常工作。錯誤日誌顯示「AH01215:SQLSTATE [HY093]:無效的參數編號:未綁定任何參數」 – ntzm