为什么php-pdo不插入值

时间:2019-04-22 04:22:49

标签: php mysql pdo

我正准备使用PDO进行简单查询。但是,当我运行它时,它不会插入。数据库称为“著名”,表名为“ pessoas”,仅包含两列(codigo和nome)。连接有效,但是当我执行连接时,返回“ Error to save”。

<?php

function getConnection(){
    $dsn = 'mysql:host=localhost;bdname=pessoas';
    $user = 'root';
    $password = 'init4289';

    try{
        $pdo = new PDO($dsn, $user, $password);
        echo 'SUCESSO AO CONECTAR!';
        return $pdo;
    }catch(PDOExeption $ex){
        echo 'erro: '. $ex->getMessage();
    }
}
?>
#end page "conexao_pdo.php"


<?php
include 'conexao_pdo.php';

$conn = getConnection();

$sql = "INSERT INTO famosos (codigo, nome) VALUES (?, ?)";

$stmt = $conn->prepare($sql);
$stmt->bindValue(1, 6);
$stmt->bindValue(2, 'Antonio');


if($stmt->execute()){
echo 'Success to save';
}else{
    echo '<p>'.'Error to save';
}
?>

1 个答案:

答案 0 :(得分:1)

您可以考虑以下内容:

  • 可能只是打字错误-bdname中的dbname应该是'mysql:host=localhost;bdname=pessoas'
  • 数据库和表名-问题中的'famous''pessoas',代码中的'pessoas''famous'
  • 通过PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION包括异常处理
  • 您的函数getConnection()在失败时应返回false

代码,根据您的问题:

<?php
function getConnection(){
    $dsn = 'mysql:host=localhost;dbname=pessoas';
    $user = 'root';
    $password = 'init4289';

    try {
        $pdo = new PDO(
            $dsn, 
            $user, 
            $password,
            array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            )           
        );
        echo 'SUCESSO AO CONECTAR!';
    } catch (PDOExeption $ex){
        echo 'Error: '. $ex->getMessage();
        return false;
    }

    return $pdo;
}
?>

<?php
include 'conexao_pdo.php';

// Connection
$conn = getConnection();
if ($conn === false) {
    exit;
}   

// Statement
try
    $sql = "INSERT INTO famosos (codigo, nome) VALUES (?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(1, 6);
    $stmt->bindValue(2, 'Antonio');
    if ($stmt->execute()) {
        echo 'Success to save';
    } else {
        echo '<p>'.'Error to save';
    }
} catch (PDOExeption $ex){
    die ('Error: '. $ex->getMessage());
}
?>