我正在尝试为用户创建一个简单的表单,以输入他/她的姓名和消息。此表单还有一个下拉菜单,用于选择此消息的对象。所以我可以给菜单中的5个人中的任何一个写一条消息。我遇到的问题是它不会提交到数据库。我认为我的问题所在的地方是在php文件中,但我不能完全指责它。我之前使用过PHP,但PDO对我来说比较新,所以请耐心等待。
以下是我的html和php文件的代码。
HTML表单文件:
<form name="gradMessage" method="POST" action="submitMessage.php">
<label>Who would you like to send this message to?</label>
<select name="person">
<option name="nick" value="nick" class="dropdown">Nick</option>
<option name="justin" value="justin" class="dropdown">Justin</option>
<option name="liam" value="liam" class="dropdown">Liam</option>
<option name="conner" value="conner" class="dropdown">Conner</option>
<option name="kyle" value="kyle" class="dropdown">Kyle</option>
</select><br>
<br>
<input type="text" id="name" name="name" title="Your name"
style="color:#888;" value="Your name" onfocus="inputFocus(this)"
onblur="inputBlur(this)"><br>
<textarea id="message" name="message" title="Message"
style="color:#888;" value="Message" onfocus="inputFocus(this)"
onblur="inputBlur(this)" rows="5" cols="25">Your message</textarea><br>
<input type="submit" name="submit" value="submit">
</form>
这是我的PHP文件submitMessage.php:
<?php
$to_data = $_POST['person'];
$from_data = $_POST['name'];
$message_data = $_POST['message'];
$pic_path_data = "test";
try {
$user = xxxxxx;
$pass = xxxxxx;
$dbh = new PDO('mysql:host=xxxxxx;dbname=xxxxxxx', $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
# the data we want to insert
$data = array( 'to' => $to_data, 'from' => $from_data, 'message' => $message_data );
// I changed $DBH to $dbh and $STH to $sth and changed to to `to` and from to `from`
# the shortcut!
$sth = $dbh->("INSERT INTO message (`to`, `from`, `message`) value (:to, :from, :message)");
$sth->execute($data);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
echo 'hi there';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
echo '$to_data';
?>
</body>
</html>
答案 0 :(得分:3)
More information on PDO prepared statements
你缺席&#34;准备&#34;。
$sth = $dbh->("INSERT...
应为$sth = $dbh->prepare("INSERT...
从那里你可以绑定准备好的声明中的变量。
使用命名占位符:
$sth = $dbh->prepare("INSERT INTO message (`to`, `from`, `message`) VALUE (:to, :from, :message)");
$sth->bindValue(':to', $to_data);
$sth->bindValue(':from', $from_data);
$sth->bindValue(':message', $message_data);
$sth->execute();
使用?
占位符的相同想法:
$sth = $dbh->prepare("INSERT INTO message (`to`, `from`, `message`) VALUE (?,?,?)");
$sth->bindValue(1, $to_data);
$sth->bindValue(2, $from_data);
$sth->bindValue(3, $message_data);
$sth->execute();