PHP:将INSERT MySQLi转换为PDO

PHP:将INSERT MySQLi转换为PDO,php,mysqli,pdo,Php,Mysqli,Pdo,我是PDO编程新手。基于我的问题,有人能帮我把MySQLi转换成PDO吗?代码如下: <?php require_once "config.php"; $photo_before = $_POST['photo_before']; $report_id = $_GET["report_id"] ?? ""; $sql_query = "UPDATE report SET photo_before ='$photo_before', time_photo_before = NOW(),

我是PDO编程新手。基于我的问题,有人能帮我把MySQLi转换成PDO吗?代码如下:

<?php
require_once "config.php";

$photo_before = $_POST['photo_before'];
$report_id = $_GET["report_id"] ?? "";

$sql_query = "UPDATE report SET photo_before ='$photo_before', time_photo_before = NOW(), ot_start = '16:00:00' WHERE report_id = '$report_id'";

if(mysqli_query($conn,$sql_query))
{
    echo "Data Save!";
}
else
{
    echo "Error!! Not Saved".mysqli_error($conn);
}

?>  

您可以这样插入

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("UPDATE report SET photo_before =?, time_photo_before = NOW(), ot_start = '16:00:00' WHERE report_id = ?");
$stmt->bind_param($photo_before,$report_id);

// set parameters and execute
$photo_before = "value";
$report_id = "value";
$stmt->execute();

您可以使用
PDO
如下:

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
  PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
  $pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
  error_log($e->getMessage());
  exit();
}
和编写的声明:

$stmt = $pdo->prepare("UPDATE report SET photo_before =?, time_photo_before = NOW(), ot_start = '16:00:00' WHERE report_id = ?");
$stmt->execute([$_POST['photo_before'],$_GET["report_id"] ?? ""]);

欢迎来到StackOverflow!到目前为止你试过什么吗?在这里,我们期待您的帮助,因为您的尝试有助于我们更好地了解您想要什么。请尝试一些操作,然后更新您的问题,以显示您在某个应用程序中遇到的特定问题。有关更多信息,请参阅,并使用。此外,请注意,您不应在SQL语句中直接使用用户输入,如
$\u POST
(即使映射到变量时也是如此)!您应该改为使用,将
$\u POST
变量绑定到参数。鉴于上述代码,您存在严重的安全漏洞。有关如何在PHP中防止SQL注入的更多信息,请参阅:)1。你在使用POST和GET吗?2.您想切换到PDO,还是在准备好的语句中使用mysqli?3.您提供的代码是用于更新的,您需要将其作为插入还是预期的行为?编辑答案后仍有一些错误:1)PDO没有connect_error属性2)bind_参数应为bindParam@catcon不,不是数组,但是这个答案合并了PDO和mysqli。PDO对象会将其称为
占位符名称、参数名称、字符串类型
@user3783243:啊,谢谢,经过快速搜索,我想我把
bindParam()
execute()
搞混了,
execute
可以绑定一个值,所以
bindvalue
实际上不需要
bindparam
绑定一个参数。只需快速提示:1。将事务用于单个查询没有意义。2.对于随机代码部分来说,没有必要说“发生了什么奇怪的事情”。这样的消息必须在所有场合都是统一的,并且在一个地方编写,而不是分散在代码中。所以最好还是离开这里alone@YourCommonSense我认为最好展示最佳实践,这样人们就可以访问答案并相应地编辑代码。但我大体上同意。我展示的示例是重载的。我已经改正了。