douba8048 2013-02-07 19:32
浏览 40
已采纳

PDO连接/准备和执行功能

I think i am getting a little head of myself with the below, what i want to do is have a one PDO and the prepare and execute called in a function.

I was trying to save having duplicate code with the PDO in every function.

If someone could point me in the right direction that would be greatfull and also any advise, i am currently trying to figure it all out from articles. then below gives me Call to a member function prepare() on a non-object in...

2 additional questions

  1. Should i put a try in the function for the execute and prepare, is this common practice?
  2. Is it possible to put the $db in a function and call it when needed so i ca put the die back in?

any help much appreciated.

ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

$config['db'] = array(
    'host' => 'localhost',
    'username' => 'root',
    'password' => 'root',
    'dbname' => 'bhill');
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'],
    $config['db']['username'], $config['db']['password']);
try {
    $db->exec("SET CHARACTER SET utf8");
    //$db = null;
}
catch (PDOException $ex) {
    print "Error!: " . $ex->getMessage() . "<br/>";
    die();
}

function update($db, $fn, $ln, $email, $offers, $vlue, $responce)
{
    $stmt = $db->prepare("insert into kkt (fName_765, lName_765, email_765, signup_765, kkt_resp_765, kkt_respSate_765, stamp_765) values (:fname, :lname, :email, :signup, :kkt_rsp, :kkt_respState, 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->bindParam(':kkt_rsp', $vlue, PDO::PARAM_STR);
    $stmt->bindParam(':kkt_respState', $responce, PDO::PARAM_STR);
    $stmt->execute();
    $stmt = null;
}

$fn = 'test';
$ln = 'test';
$email = 'tesst@test,com';
$offers = '1';
$vlue = 'value';
$responce = 'resp';

update($db, $fn, $ln, $email, $offers, $vlue, $responce);
  • 写回答

1条回答 默认 最新

  • dousi2553 2013-02-07 19:34
    关注

    You are doing:

    $db = null;
    

    after you set the encoding. Which basically removes the instance.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含