大家好,我一直在玩 PDO,并且正在慢慢地将一些旧代码转换为这个。
有点卡在一些事情上,努力寻找我需要的东西。
我遇到的问题是:
- 有
$db
一个函数或排序,所以它只有在我调用它时才打开,我只想管理这个的一个实例 - 检查执行是否成功,如果没有返回值等。
此外,关于以下代码的任何建议都会非常完整,因为我是从网络上收集的。
当前代码:
//Database Array
$config['db'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'dbname' => 'root');
//New PDO
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
//Check connection is ok
try {
$db->exec("SET CHARACTER SET utf8");
}
catch (PDOException $ex) {
print "Error!: " . $ex->getMessage() . "<br/>";
die();
}
//Update users function
function update($db, $fn, $ln, $email, $offers, $vlue, $responce) {
$stmt = $db->prepare("insert into kkt (fName_765, lName_765, email_765, signup_765, stamp_765) values (:fname, :lname, :email, :signup, NOW())");
$stmt->bindParam(':fname', $fn, PDO::PARAM_STR);
$stmt->bindParam(':lname', $ln, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':signup', $offers, PDO::PARAM_STR);
$stmt->execute();
print $db->lastInsertId();
$stmt = null;
}
//Test Attributes
$fn = 'test';
$ln = 'test';
$email = 'tesst@test,com';
$offers = '1';
update($db, $fn, $ln, $email, $offers, $vlue, $responce);
提前感谢任何帮助/提示
编辑代码:
//Database Array
$config['db'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'dbname' => 'local');
//New PDO
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Check connection is ok
try {
$db->exec("SET CHARACTER SET utf8");
}
catch (PDOException $ex) {
print "Error!: " . $ex->getMessage() . "<br/>";
die();
}
//Update users function
function update($db, $fn, $ln, $email, $offers, $vlue, $responce)
{
$stmt = $db->prepare("insert into local (fName_765, lName_765, email_765, signup_765) values (:fname, :lname, :email, :signup, NOW())");
$stmt->bindParam(':fname', $fn, PDO::PARAM_STR);
$stmt->bindParam(':lname', $ln, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':signup', $offers, PDO::PARAM_STR);
try {
$stmt->execute();
print $db->lastInsertId(); //show ID
return true;
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>"; // show error
return false;
}
}
//Test Attributes
$fn = 'test';
$ln = 'test';
$email = 'tesst@test,com';
$offers = '1';
if (!update($db, $fn, $ln, $email, $offers, $vlue, $responce)) {
echo "no update there is a slight problem";
} else {
echo "it seemed to work";
}
似乎到了那里,上面的作品看起来如何