问题
I'm new in PDO programming. Based on my question, can anyone help me to convert MySQLi to PDO? Below is the code:
<?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);
}
?>
Hope there's a kind people to help me. Thanks
回答1:
You can use PDO
as this:
$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();
}
and prepared statements:
$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"] ?? ""]);
回答2:
You can insert like this
<?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();
Hope this will work for you and in case you need the source https://www.w3schools.com/php/php_mysql_prepared_statements.asp
来源:https://stackoverflow.com/questions/59132158/php-convert-insert-mysqli-to-pdo