我在使用PDO并尝试将表单数据插入数据库中时正在寻找一些建议。
我创建了一个通过构造连接到数据库的类,当表单被填写时,我想使用一种方法来接受数据以将其插入数据库。
这可能吗?还是我需要通过一种程序方法来解决它?
我的插入语句如下:
class Post extends Database
{
public function postMessage($username, $message)
{
if (isset($_SERVER['POST'])){
$connection->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("INSERT INTO messages
(username, message) VALUES (:user, :message)");
$statement->bindParam(':username', $username);
$statement->bindParam(':message', $message);
$statement->execute();
echo "Message has been sent";
} else {
exit("Need to enter a message");
}
}
}
答案 0 :(得分:0)
删除if-else语句(像这样):
class Post extends Database
{
public function postMessage($username, $message)
{
if(!empty($username) && !empty($password))
{
$this->connection->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("INSERT INTO messages
(username, message) VALUES (:user, :message)");
$statement->bindParam(':username', $username);
$statement->bindParam(':message', $message);
if($statement->execute())
echo "Message has been sent";
else
echo "Something wants wrong!";
}
else
{
echo "Please fill all fields!";
}
}
}
创建对象并调用函数:
$post = new Post;
echo $post->postMessage("John", "Hello, world");