gpt4 book ai didi

PHP 使用准备语句插入查询

转载 作者:行者123 更新时间:2023-11-29 23:00:07 25 4
gpt4 key购买 nike

我创建了一个插入表单。我正在使用准备语句对 MySQL 进行插入操作,但它不起作用。我不明白出了什么问题。请帮我解决这个问题。我这样做对吗?

插入.php

<?php

include('dbconn.php');
session_start();
$_SESSION['example']='Session Created';
$srn = $_POST['srn'];
$client = $_POST['client']; // required
$category = $_POST['category'];
$sd = $_POST['sd']; // required
$fd = $_POST['fd'];

$host = "localhost";
$user = "root";
$pwd = "root";
$db = "eservice";
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
$sql = "Insert into main(client,category,sd,fd) values(:client,:category,:sd,:fd)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':client',$_POST['client'],PDO::PARAM_STR);
$stmt->bindParam(':category',$_POST['category'],PDO::PARAM_STR);
$stmt->bindParam(':sd',$_POST['sd'],PDO::PARAM_STR);
$stmt->bindParam(':fd',$_POST['fd'],PDO::PARAM_STR);
$stmt->execute();

?>

dbconn.php

<?php
$host = "localhost";
$user = "root";
$pwd = "root";
$db = "eservice";

$mysqli = new mysqli($host,$user,$pwd,$db);
/* ESTABLISH CONNECTION */
if (mysqli_connect_errno()) {
echo "Failed to connect to mysql : " . mysqli_connect_error();
exit();
}
?>

最佳答案

提出你所遇到的错误总是好的。
您正在使用两种不同的数据库连接类型 pdo 和 mysqli。您只需要一个。

我将您的代码精简到最少。

<?php

$host = "localhost";
$user = "root";
$pwd = "root";
$db = "eservice";
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pwd);

//$srn = $_POST['srn'];
$client = $_POST['client']; // required
$category = $_POST['category'];
$sd = $_POST['sd']; // required
$fd = $_POST['fd'];

// make sure client and sd are set here

$stmt = $pdo->prepare("
INSERT INTO
main
(client,category,sd,fd)
VALUES
(:client,:category,:sd,:fd)
");
$success = $stmt->execute([
'client' => $client,
'category' => $category,
'sd' => $sd,
'fd' => $fd
]);

关于PHP 使用准备语句插入查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28536313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com