我想将数据插入到phpmyadmin表中,类似的代码在另一个页面中工作,但它在这个中不起作用。这是代码:
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
try {
$conn = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch (PDOException $e) {
echo $e->getMessage();
}
if ( isset($_POST['NomPrenom']) && isset($_POST['date']) && isset($_POST['email']) && isset($_POST['description']) ) {
$NomPrenom = $_POST['NomPrenom'];
$date = $_POST['date'];
$email = $_POST['email'];
$description = $_POST['description'];
try {
$sql = "INSERT INTO demande (NomPrenom,date,email,description)
VALUES ('$NomPrenom','$date','$email','$description')";
$stmt = $conn->prepare($sql);
if ($stmt->execute(array(
$NomPrenom,
$date,
$email,
$description
))) {
echo "Data inserted";
} else {
echo "could not insert";
}
}
catch (Exception $ex) {
error_log($ex->getMessage());
}
}
?>
当我提交页面时刷新没有错误,表格中没有添加任何内容。 这是数据库中的表 table named demande
答案 0 :(得分:0)
您的查询构造错误,您需要在要准备的查询中放置位置参数,然后在执行时传递这些参数的值。
$sql = "INSERT INTO demande (NomPrenom,date,email,description)
VALUES (?,?,?,?)";
$stmt = $conn->prepare($sql);
if ($stmt->execute(array($NomPrenom,$date,$email,$description))) {
echo "Data inserted";
} else {
echo "could not insert";
}
或使用像这样的命名参数
$sql = "INSERT INTO demande (NomPrenom,date,email,description)
VALUES (:nom, :dat, :em, :desc)";
$stmt = $conn->prepare($sql);
$params = array(':nom'=>$NomPrenom,
':dat'=>$date,
':em'=>$email,
':desc'=>$description);
if ( $stmt->execute($params) ) {
echo "Data inserted";
} else {
echo "could not insert";
}