我已经用完了选项,现在我只是盯着我的屏幕,希望我的代码能够开始工作,尽管我没有改变它......任何帮助都会受到赞赏。我是一个新手......第一个PHP项目,所以要善良。我用Google搜索并搜索了这个论坛,似乎无法找到适合我的解决方案。
我正在尝试将表单中的数据插入到数据库中。这是代码:
<?php
error_reporting(E_all);
ini_set('display_errors', 1);
include $_SERVER['DOCUMENT_ROOT'] . 'rstools/inc/helpers.inc.php';
if(!isset($_POST['reg'])){
include 'form.html.php';
}
else {
if($_POST['firstname'] == '')
{
$registerError = 'All fields are required. You did not enter your first name.';
include 'form.html.php';
}
elseif($_POST['lastname'] == '')
{
$registerError = 'All fields are required. You did not enter your last name.';
include 'form.html.php';
}
elseif($_POST['phone'] == '')
{
$registerError = 'All fields are required. You did not enter your phone number.';
include 'form.html.php';
}
elseif($_POST['email'] == '')
{
$registerError = 'All fields are required. You did not enter your e-mail address.';
include 'form.html.php';
}
elseif($_POST['ward'] == '')
{
$registerError = 'All fields are required. You did not select your ward from the list.';
include 'form.html.php';
}
else
{
try
{
// This include statement does not work. $pdo is undefined if used.
// include '/rstools/inc/db.inc.php';
// The code from db.inc.php is show below without the leading <?php
// When this code is included here, it works perfectly.
$dsn = 'mysql:host=localhost;dbname=learnpkp_rstools;charset=utf8';
$username = 'user';
$pwd = 'pwd';
try
{
$pdo = new PDO($dsn, $username, $pwd);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
$error = 'Unable to connect to the database server.' . $e;
include 'error.html.php';
exit();
}
// End of db.inc.php file text
$sql = "INSERT INTO santashelpersvolunteers (firstname, lastname, ward, phone, email)
VALUES (:firstname, :lastname, :ward, :phone, :email)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':firstname',$_POST['firstname']);
$stmt->bindValue(':lastname',$_POST['lastname']);
$stmt->bindValue(':ward',$_POST['ward']);
$stmt->bindValue(':phone',$_POST['phone']);
$stmt->bindValue(':email',$_POST['email']);
$stmt->execute();
}
catch (PDOException $e)
{
$error = 'Error during registration: ' . $e->getMessage();
include 'error.html.php';
}
$name = $_POST['firstname'] . ' ' . $_POST['lastname'];
include 'thankyou.html.php';
}
}
当脚本运行时,我没有收到任何错误(即,error.html.php没有显示)。我只看到一个白色的网页... @MichaelBerkowski发现这是一个范围问题...上面添加了完整的代码:
我无法弄清楚范围问题。我没有使用任何功能。基本上,代码设置为检查表单是否已提交,如果没有,则显示包含表单的页面。然后,如果它已被提交,它会执行一些简单的错误检查,然后将表单数据插入到数据库中。也许我这样做错了......
答案 0 :(得分:1)
a)使用套接字,而不是localhost;
b)使用模型:
try{
...
} catch(PDOExeption $e){
...
} catch(Exeption $e){
...
} finally {
...
// check the connection status
}
因为你无法确定exeption的类型
答案 1 :(得分:0)
出于某种原因,当我使用include
添加一段代码来访问数据库时,$ pdo将是未定义的。所以我创建了一个新文件“insertvolunteer.inc.php”,在该文件中我添加了数据库访问命令和SQL命令来插入数据。然后我include
在我的流程中的那个单个文件,它似乎工作。
不是一个很好的解决方案,因为每次调用数据库都需要一个单独的.inc.php文件......但是它有效......
感谢大家的投入。