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 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制