PDOStatement $语句执行http 500错误

时间:2015-08-02 16:43:05

标签: php mysql

我的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显示

如果您想查看错误,请转到To see the error

通过下面的代码,我调用方法将对象保存在我的小项目中,我将把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;
    }

}

1 个答案:

答案 0 :(得分:1)

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

我只是改变方法执行并按照你的建议放置try / catch和bingo。现在正在努力!!!!

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;
}
相关问题