我正准备使用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';
}
?>
答案 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());
}
?>