2017-08-14 65 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

对不起,我现在看到这个错误:-)你应该在日期后删除';')'我会在我的答案中改变这个。 –