如何在OOP PDO中编写编写和执行语句? [英] How to write prepare and execute statements in OOP PDO?

查看:75
本文介绍了如何在OOP PDO中编写编写和执行语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有一个小问题.我是OOP的新手,所以这个问题听起来很愚蠢,但是我找不到任何有用的信息.

I have a little problem here.I am new to OOP, so the question might sound stupid, but I couldn't find any helpful information.

我正在尝试登录数据库并将用户输入的值放入数据库中,我想问你,我应该在哪里编写PDO prepare和execute语句?我知道它们是必需的,但我不知道如何正确编写它……除此之外,我还收到错误消息"PDO类的对象无法在第24行转换为字符串".谢谢您的帮助,这是我的代码:

I am trying to login to the database and put the user's entered values inside of it and I want to ask you, in which place should I write PDO prepare and execute statements? I know they're needed, but I have no idea how to write it corretly...Besides that, I also got an error "Object of class PDO could not be converted to string on line 24". Thank you for any help, here's my code:

<?php
class Connection {
public $connection;
public $dbHost = 'localhost';
public $dbName = 'employees';
public $charset = 'charset=utf8';
public $dbUser = 'root';
public $dbPassword = '';

public function __construct() {
    try {
        $this->connection = new PDO ("mysql:host=$this->dbHost;$this->dbName;$this->dbUser;
        $this->dbPassword");
        $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }
    catch (PDOException $e) {
        echo "There is something wrong with the database".$e->getMessage();
    }
}
function insertUserValues($tableName, $data) {
    $query = "INSERT INTO ".$tableName."(";
    $query .= implode (",",array_keys($data)).') VALUES (';
    $query .= "'" . implode ("','",array_values($data))."')";
}
}
$users = new Connection();
?>

推荐答案

我对bru的解释不是很满意,但我只是看到很长一段时间后仍然没有答案.我已经创建了一个基本类供您使用PDO插入值,希望它会为您指明正确的方向,我还将为您共享一些有用的链接.

I'm not really good with explanations bru, but I just see that there's no answer after a long time. I have created a basic class for you to insert values using PDO, I hope it will point you to the correct direction, I will also share some useful links for you.

首先连接.

我可以看到您已经在课堂上完成了连接,但是下面是正确的最佳pdo连接.

I can see you have done the connection already in your class, but below is the proper best pdo connection.

    $host = '127.0.0.1';
    $db   = 'YourDatabase';
    $user = 'YourDBUser';
    $pass = 'YourDBPass';
    $charset = 'utf8';

    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
    $opt = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
            ];

$dbh = new PDO($dsn, $user, $pass, $opt);

这就是设置正确的PDO连接的方式. dns 代表数据源名称,是上述 https:的引用: //phpdelusions.net/pdo#dsn 这个家伙解释得更好.您需要知道的一切.

that is how you set up proper PDO connection. dns stands for data source name Reference of the above https://phpdelusions.net/pdo#dsn this guy explains it better. everything you need to know.

现在您如何将这种联系与您的班级放在一起?

Now how do you put that connection all together with your class?

好吧,我将创建一个收集pdoClass.php的文件,并从该类中进行工作.

well I will create a file collect pdoClass.php and work from that class.

<?php
class Connection
{
    private $host = "127.0.0.1";
    private $dbName = "YourDB";
    private $user = "YourUser";
    private $pass = "YourPass";
    private $charset = 'utf8';

    private $dbh;
    private $error;
    private $stmt;

    //connection
    public function __construct()
    {
        $dsn     = "mysql:host=" . $this->host . ";dbname=" . $this->dbName . ";charset=" . $this->charset;
        $options = array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false
        );

        try {
            // setup connection
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
        }
        //catch any errors
        catch (PDOException $e) {
            $this->error = $e->getMessage();
        }

    }

    //prepare statement
    public function insertUserValues($query)
    {
        $this->stmt = $this->dbh->prepare($query);
    }

    //bind values
    public function bind($param, $value, $type = null)
    {
        if (is_null($type)) {
            switch (true) {
                case is_int($value):
                    $type = PDO::PARAM_INT;
                    break;
                case is_bool($value):
                    $type = PDO::PARAM_BOOL;
                    break;
                case is_null($value):
                    $type = PDO::PARAM_NULL;
                    break;
                default:
                    $type = PDO::PARAM_STR;
            }
        }
        //actual value binding
        $this->stmt->bindValue($param, $value, $type);
    }
    //execute statement
    public function run()
    {
        return $this->stmt->execute();
    }
}

?>

基本上,这是设置数据库和在数据库中插入的功能所需的全部,我尝试对某些部分进行注释.

basically that's all you need to setup the database and the function to insert in your db, I have tried to comment some sections.

现在要使用此类创建index.php或您喜欢的任何内容.然后加入课程

Now to use this class create index.php or what ever you like. then include the class

<?php
    include'pdoClass.php';


    $users = new Connection();

    $users->insertUserValues('INSERT INTO test (name, age, description) VALUES(?,?,?)');
    $users->bind(1, 'User'); //bind each value
    $users->bind(2, 391); // bind
    $users->bind(3, 'This is a value');
    if($database->run()){

        echo "record inserted";
    }

?>

完成,如果您有任何疑问或希望我向您解释任何内容,请在下面发表评论,我会尽力为您提供帮助.

Done, if you have any question or like me to explain anything, feel free to comment below I will try my best to assist u.

:如果需要获取结果,还可以在该类中创建一个新函数

Edit : if you need to fetch the results, you can also make a new function in the class,

单行:

public function SingleRow(){
      $this->run();
      return $this->stmt->fetch();
  }

请参阅我们使用fetch();仅获取一行.大多数人在获取结果时都会像这样fetch(PDO::FETCH_ASSOC)那样获取它们,但是由于我们进行了正确的连接并在连接中定义了默认的获取模式,因此我们不需要仅使用fetch();

see we use fetch(); to only fetch one row. most people when they fetch results will fetch them like this fetch(PDO::FETCH_ASSOC) but because we did a proper connection and defined our default fetch mode in the connection we don't need all that we can just use fetch();

要在index.php文件上显示这些结果,这就是您要执行的操作:

to display those results on your index.php file this is how you will do :

$users->insertUserValues("SELECT name, age, description FROM test WHERE name = :name");
$users->bind(':name','joe');
$row = $users->SingleRow();

echo '<pre>';
print_r($row);
echo '</pre>';

这会将joe的结果显示为数组.

this will display joe's result as an array.

从数据库获取所有结果

我们还有另一个功能来显示所有结果.

we do another function to display all results.

 public function All(){
          $this->run();
          return $this->stmt->fetchall();
      }

您现在看到的区别是,我们使用fetchall()是因为我们需要所有结果.

You see the difference now we use fetchall() because we want all the results.

 $users->insertUserValues("SELECT *  FROM test");
    $row = $users->All();

    echo '<pre>';
    print_r($row);
    echo '</pre>';

这篇关于如何在OOP PDO中编写编写和执行语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆