2017-08-14 63 views
0

我想在PHP中構建一個小私人消息系統,我使用PDO作爲數據庫的連接。我有最多的工作excrat最重要的部分。INSERT私人消息系統PDO php

我無法獲得插入消息來向數據庫寫入任何東西,所以我會喜歡一些幫助。

我會先發布我的數據庫,以便大家可以看到我們在這裏工作的內容。 開始與我的用戶

id int(10) UN AI PK 
username varchar(30) 
password varchar(100) 
regdate datetime 

這是我嘗試寫入信息給

id int(11) AI PK 
from_user varchar(45) 
to_user varchar(45) 
subject varchar(400) 
message text 
date date 
read tinyint(4) 

我已經嘗試了幾個不同勢代碼來得到它的工作 我現在貼我的消息表根據我的錯誤檢查代碼說,郵件成功發送...

$sql = " 
INSERT INTO private_messages VALUES('',$user, 
$to_user','$subject',$message','$date','0') 
"; 

    echo "Youre message was succesfully sent..."; 

但這不起作用,我知道這在使用PDO時可能不是正確的方式。

我也試過這種

$query =$dbh->prepare("INSERT INTO private_messages(user, to_user, subject, 
message, 
date); 
VALUES('',$user, $to_user','$subject',$message','$date','0') 
"); 

$query->bindParam(":user", $user); 
$query->bindParam(":to_user", $to_user); 
$query->bindParam(":subject", $subject); 
$query->bindParam(":message", $message); 

if ($query->execute()) { 
    $success = true; 
} 

但後來我得到致命錯誤:未捕獲PDOException:SQLSTATE [42000]:語法錯誤或訪問衝突:1064

我也將使用後的形式IM如果這可以是任何值

echo " 
<form action='compose.inc.php' method='POST'> 
<table> 
<tr> 
<td>To: </td> 
<td><input type='text' name='to_user'/></td> 
</tr> 
<tr> 
<td>Subject: </td> 
<td><input type='text' name='subject'/></td> 
</tr> 
<tr> 
<td>Message:</td> 
<td><textarea name='message' rows='10' cols='50'></textarea></td> 
</tr> 
<tr> 
<td></td> 
<td colspan='2'><input type='submit' name='submit' value='Send Message'/> 
</td> 
</r> 
</table> 
</form> 

    "; 

的時候做了以下這個https://www.youtube.com/watch?v=BED_yMC7qv0此消息系香港專業教育學院,其使用的mysqli和我一直在試圖解碼它到PDO,我認爲問題在於

所以簡短的回顧 我的錯誤檢查說我的消息被髮送。 沒有寫入我的數據庫。 即時嘗試使用PDO。

如果我找不到解決方案,我很樂意指點教程或書籍或任何與PDO有關的消息系統。 此致敬禮/羅伯特

+1

您應該[閱讀有關準備好的陳述的手冊。](http://php.net/manual/en/pdo.prepared-statements.php)。綁定變量時,您需要添加佔位符而不是連接查詢中的值。 –

+0

你也有一個無與倫比的單引號:'$ to_user」,' –

+0

我已刪除該帖,didnt helpt我也用$ SQL =「 \t INSERT INTO private_messages(用戶)和 \t VALUES(:用戶, )$ stmt = $ dbh-> prepare($ sql); $ stmt-> bindValue(「:user」,$ _POST [「user」]); if($ stmt-> execute()){ \t \t $成功= true; \t \t} < - 一個簡短的版本,但以這種方式與所有值c – Robert

回答

1

而不是將變量插入到查詢中,你通過綁定它們來做到這一點。

$query =$dbh->prepare("INSERT INTO private_messages (user,to_user,subject,message,date) 
VALUES(:user,:to_user,:subject,:message,NOW())"); 

$query->bindParam(":user", $user); 
$query->bindParam(":to_user", $to_user); 
$query->bindParam(":subject", $subject); 
$query->bindParam(":message", $message); 

if ($query->execute()) { 
    $success = true; 
} 

此外,您應該將值的數量與列的數量相匹配。

+0

我嘗試了一些simillar,但發生了什麼s is this致命錯誤:未捕獲的PDOException:SQLSTATE [42000]:語法錯誤或訪問衝突:1064您的SQLuse在'; VALUES(?,?,?,?,?)'在37行的第1行):PDO-> prepare('INSERT INTO pri ...')#1但是我使用幾乎相同的方法來註冊一個用戶,工作正常。 – Robert

+0

'this'是什麼意思? –

+0

對不起,我現在看到這個錯誤:-)你應該在日期後刪除';')'我會在我的答案中改變這個。 –