PDOStatement执行http 500错误


PDOStatement $statement execute http 500 error

我的PDOStatement $语句产生HTTP 500,我不知道为什么!下面是我的代码:

final class ContatoDao {
private $db = null;
public function __destruct() {
    //Fecha a conexão
    $this->db = null;
}
private function getDb() {
    if ($this->db !== null) {
        return $this->db;
    }
    $config = Config::getConfig("db");
    try {
        $this->db = new PDO($config['dsn'], $config['username'], $config['password']);
    } catch (Exception $ex) {
        throw new Exception('Conexao com o banco de dados falhou: ' . $ex->getMessage());
    }
    return $this->db;
}
private function execute($sql, Contato $contato) {
    $statement = $this->getDb()->prepare($sql);
    $this->executeStatement($statement, $this->getParams($contato));
    if (!$contato->getId()) {
        return $this->findById($this->getDb()->lastInsertId());
    }
    if (!$statement->rowCount()) {
        throw new NotFoundException('Contato with ID "' . $contato->getId() . '" não existe.');
    }
    return $contato;
}
private function executeStatement(PDOStatement $statement, array $params) {
    if (!$statement->execute($params)) {
        self::throwDbError($this->getDb()->errorInfo());
    }
}
private function query($sql) {
    $statement = $this->getDb()->query($sql, PDO::FETCH_ASSOC);
    if ($statement === false) {
        self::throwDbError($this->getDb()->errorInfo());
    }
    return $statement;
}
/**
 * Recebe id para efetuar a busca 
 * @param type $id 
 * @return retorna o objeto 'Contato
 */
public function findById($id) {
    $row = $this->query('SELECT * FROM contatos WHERE deleted = 0 and id = ' . (int) $id)->fetch();
    if (!$row) {
        return null;
    }
    $contato = new Contato();
    ContatoMapper::map($contato, $row);
    return $contato;
}
/**
 * Salva o objeto Contato na base de dados.
 * @param Contato $contato
 * @return type
 */
private function insert(Contato $contato) {
    $contato->setDeletado(false);
    $sql = '
        INSERT INTO contatos (id, nome, email, msg, phone, deletado)
            VALUES (:id, :nome, :email, :msg, :phone, :deletado)';
    return $this->execute($sql, $contato);
}
/**
 * Efetua atualização.
 * @param Contato $contato para fazer atualização.
 * @return type void
 */
private function update(Contato $contato) {
    $sql = '
        UPDATE contatos SET
            nome = :nome,
            email = :email,
            msg = :msg,
            phone = :phone,
            deletado = :deletado,
        WHERE
            id = :id';
    return $this->execute($sql, $contato);
}
/**
 * function para salvar Contato $contato base de dados
 * @param function recebe Contato $contato.
 * @return type void
 */
public function save(Contato $contato) {
    if ($contato->getId() === null) {
        return $this->insert($contato);
    }
    return $this->update($contato);
}
private function getParams(Contato $contato) {
    $params = array(
        ':id' => $contato->getId(),
        ':nome' => $contato->getNome(),
        ':email' => $contato->getEmail(),
        ':msg' => $contato->getMensagem(),
        ':phone' => $contato->getPhone(),
        ':deletado' => $contato->getDeletado(),
    );
    return $params;
}
private static function throwDbError(array $errorInfo) {
    // TODO log error, send email, etc.
    throw new Exception('DB error [' . $errorInfo[0] . ', ' . $errorInfo[1] . ']: ' . $errorInfo[2]);
}
}

我试图在Mysql中保存对象Contato,它工作,但之后错误http 500显示

如果你想看到错误就直接去查看错误

通过下面的代码,我调用方法来保存我的小项目中的对象,我将放置try/catch。

  <?php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
$errors = array();
$contato = new Contato();
if (array_key_exists('cancel', $_POST)) {
    Utils::redirect('home');
} elseif (array_key_exists('save', $_POST)) {
    $data = array(
        'nome' => $_POST['contato']['nome'],
        'email' => $_POST['contato']['email'],
        'msg' => $_POST['contato']['msg'],
        'phone' => $_POST['contato']['phone'],
    );
    ContatoMapper::map($contato, $data);
    $errors = ContatoValidator::validade($contato);
    if (empty($errors)) {
        Utils::sendEmail($contato);
        $contatoDao = new ContatoDao();
        $contato = $contatoDao->save($contato);
        Utils::redirect('home');
    } else {
        echo $errors;        
    }
 }

这是我的配置类,我用它来检索连接MySQL的信息

<?php
/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
final class Config {
    /** @var array config data */
    private static $data = null;

    /**
     * @return array
     * @throws Exception
     */
    public static function getConfig($section = null) {
        if ($section === null) {
            return self::getData();
        }
        $data = self::getData();
        if (!array_key_exists($section, $data)) {
            throw new Exception('Unknown config section: ' . $section);
        }
        return $data[$section];
    }
    /**
     * @return array
     */
    private static function getData() {
        if (self::$data !== null) {
            return self::$data;
        }
        self::$data = parse_ini_file('../config/config.ini', true);
        return self::$data;
    }
}

RiggsFolly感谢您对我的问题和u_mulder的帮助和关注。

我只是改变了execute方法,并按照你的建议放入try/catch,然后就好了。现在正在工作!!!!

private function execute($sql, Contato $contato) {
    $statement = $this->getDb()->prepare($sql);
    $this->executeStatement($statement, $this->getParams($contato));
    if (!$contato->getId()) {
        return $this->findById($this->getDb()->lastInsertId());
    }
    if (!$statement->rowCount()) {
        throw new NotFoundException('Contato with ID "' . $contato->getId() . '" não existe.');
    }
    return $contato;
}
修改后

:

private function execute($sql, Contato $contato) {
    try {
        $statement = $this->getDb()->prepare($sql);
        $this->executeStatement($statement, $this->getParams($contato));
        if (!$contato->getId()) {
            return $this->findById($this->getDb()->lastInsertId());
        }
        if (!$statement->rowCount()) {
            throw new NotFoundException('Contato with ID "' . $contato->getId() . '" não existe.');
        }            
    } catch (Exception $ex) {
        $ex->getTraceAsString();
    }
    return $contato;
}