PHP 使用准备语句插入查询

标签 php mysql

我创建了一个插入表单。我正在使用准备语句对 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/

相关文章:

javascript - 将数据插入 MySQL 数据库后自动运行查询

php - 如何在php中将时间转换为字符串

c# - 尝试使用 ZeroMQ 构建分布式爬虫

php - CDbCommand::fetchColumn() failed: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active

mysql - 如何将MySQL服务器安装到WINDOWS 10? MySQL 安装程序显示正在升级而不是安装程序

php - 错误消息不适用于 PHP 用户检查

mysql - 如何对在 SQL Server 2008 中存储为 Nvarchar 的会计月进行排序

php - 使用 PHP 类来运行 mysql 查询这样不好吗?

php - 创建评论部分 - 最佳方法?

php - 正则表达式用于查找包含在两个小节之间并包含某些单词的字符串