doqrjrc95405 2018-07-11 13:16
浏览 55

为什么我在PDO中总是布尔错误?

I have a mySQL class to connect and execute my queries from and in to a database. When i connect to the database everything is working correctly. When i try to put something into the database, then it's also ok, but when i try to get something from it, I get a boolean (true) error, regardless the input. I assume it must return an object but it returns a boolean. Why is that so?

My code is shown below:

class Database {

function __construct() { 
    // пустой инициализатор 

    $this->set_connection(); // нужно ли автоматически инициализировать?
}

private $dbchar = "UTF8";
private $dbuser = "admin";
private $dbpass = "1234";
private $dbhost = "localhost";
private $dbname = "core_db";
private $dbpref = "pre_";

private $link;

private function set_connection() {

    $dsn = "mysql:host=".$this->dbhost.";dbname=".$this->dbname.";charset=".$this->dbchar;

    $opt = array(
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        //PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
        // Выключает режим эмуляции! если у вас проблемы с LIMIT ?,?
        PDO::ATTR_EMULATE_PREPARES   => TRUE
    );
    try {
        $this->link = new PDO($dsn, $this->dbuser, $this->dbpass, $opt);
        if (!$this->link) throw new Exception("Cannot connect to database!", 4);

    } catch (Exception $e) {
        die("Error! " . $e->getMessage());
    }
}

// Получаем ссылку на соединенние с базой 

function get_connection() {

    return $this->link; 
}

/*
    НЕ УДАЛЯТЬ ---------------------------------------------------------
    Запросы можно использовать вот так.................!
    # просто испольняет SQL запрос // INSERT. DELETE OR UPDATE
    $this->execute_query($sql); 
    $this->execute_query($sql, $data);  
    # all rows
    $result = $this->execute_query($sql, $data)->fetchAll();
    foreach ($result as $row) echo $row['name'];
    # one row
    $row = $this->execute_query($sql, $data)->fetch();
    # one cell
    $count = $this->execute_query($sql)->fetchColumn(); // можно использовать для подсчета ячеекы
    # column
    $ids = $this->execute_query($sql)->fetchAll(PDO::FETCH_COLUMN);
    НЕ УДАЛЯТЬ ---------------------------------------------------------
*/

// метод выполнения запроса SQL !!!
// Использ.  $sql = SELECT * FROM table WHERE a = ? and b = ?
// Использ.  $data = array('a', 'b');

function execute_query($sql, $elements=false) {

    $error_exist = false;
    $data = false;

    try {
        if (empty($sql)) throw new RuntimeException('no SQL!');

        $stmt = $this->get_connection()->prepare($sql);

        if (!$stmt) throw new RuntimeException('SQL preparing failure!');

        if (!$elements) {
            $data = $stmt->execute();
        } else {
            $data = $stmt->execute($elements);
        }

        if (!$data) throw new RuntimeException('SQL execution failure!');

    } catch (Exception $e) {
        $error_exist = true;
        $data = $e->getMessage();
    }

    return array('error' => $error_exist, 'result' => $data);
}



// Закрываем соединение с базой
function close_connection() {
    $this->link = null;
}

function __destructor() {
    $this->close_connection();
}

}

The index.php file itself is shown here instead:

$sql = "SELECT * FROM prava WHERE test_id = ?";

$r = $db->execute_query($sql, ['1']);

var_dump($r);
  • 写回答

1条回答 默认 最新

  • duanfenhui5511 2018-07-11 16:59
    关注

    Finaly fix this:

    So what i done wrong? i return executing result but i need a return a object then make a fetch() Daaammnnn..

    Thanx for @user3783243

    So this code:

       if (!$elements) {
            $data = $stmt->execute();
        } else {
            $data = $stmt->execute($elements);
        }
    

    Must be this code:

       if (!$elements) {
            $data = $stmt->execute();
            return $data;
        } else {
            $stmt->execute($elements);
            return $stmt // and then get a fetch from object 
        }
    

    as example.

    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大