我目前正在学习编码并努力解决如何正确使用 PDO 来构建基于 PHP/MySQL 的应用程序。以下代码应该从 HTML 表单中获取用户数据并插入到数据库中,但是当表单提交时页面变为空白,没有返回错误消息并且没有任何内容添加到数据库中。
感激地收到所有建议:
<?php
if ( empty( $_POST ) ){
?>
<form name='registration' action='user_register.php' method='POST'>
<label for 'title'>Title: </label>
<input type="text" name="title" />
<label for 'url'>URL: </label>
<input type="text" name="url" />
<label for 'contact'>Contact: </label>
<input type="text" name="contact" />
<label for 'category'>Category: </label>
<input type="text" name="category" />
<label for 'location'>Location: </label>
<input type="text" name="location" />
<label for 'founded'>Founded: </label>
<input type="text" name="founded" />
<label for 'rss'>RSS: </label>
<input type="text" name="rss" />
<label for 'twitter'>Twitter: </label>
<input type="text" name="twitter" />
<label for 'facebook'>Facebook: </label>
<input type="text" name="facebook" />
<label for 'google'>Google: </label>
<input type="text" name="google" />
<label for 'youtube'>YouTube: </label>
<input type="text" name="youtube" />
<label for 'pinterest'>Pinterest: </label>
<input type="text" name="pinterest" />
<label for 'instagram'>Instagram: </label>
<input type="text" name="instagram" />
<button type="submit">Submit</button>
</form>
<?php
} else {
try {
$db_user = 'testuser';
$db_pass = 'testpassword';
$db = new PDO( 'mysql:host=localhost;dbname=testdatabase', $db_user, $db_pass );
$form = $_POST;
$title = $form[ 'title' ];
$url = $form[ 'url' ];
$contact = $form[ 'contact' ];
$category = $form[ 'category' ];
$location = $form[ 'location' ];
$founded = $form[ 'founded' ];
$rss = $form[ 'rss' ];
$twitter = $form[ 'twitter' ];
$facebook = $form[ 'facebook' ];
$google = $form[ 'google' ];
$youtube = $form[ 'youtube' ];
$pinterest = $form[ 'pinterest' ];
$instagram = $form[ 'instagram' ];
$sql = "INSERT INTO testtable (
title, url, contact, category, location,
founded, rss, twitter, facebook,
google, youtube, pinterest, instagram )
VALUES (
:title, :url, :contact, :category,
:location, :founded, :rss, :twitter,
:facebook, :google, :youtube, :pinterest, :instagram )";
$query = $db->prepare( $sql );
$query->execute( array( ':title'=>$title, ':url'=>$url, ':contact'=>$contact, ':category'=>$category, ':location'=>$location, ':founded'=>$founded, ':rss'=>$rss, ':twitter'=>$twitter, ':facebook'=>$facebook, ':google'=>$google, ':youtube'=>$youtube, ':pinterest'=>$pinterest, ':instagram'=>$instagram ) );
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>