我有以下变量从HTML抓取数据:
$workcarriedout = trim($_POST["workcarriedout"]);
以下语句将此条目插入SQL数据库(而不是mySQL数据库):
$stmt = $db->prepare("INSERT INTO [dbo].[server_log_entries] (work_carried_out)
values ('".$workcarriedout."')");
这在输入变量的数据包含单引号之前完全正常。
有人可以告诉我如何使用单引号导入数据吗?
编辑:如果这有所不同,那么代码是:
<?php
require_once('../settings.php');
// Get the form fields and remove whitespace
var_dump($_POST);
$datetime = trim($_POST["datetime"]);
$servername = trim($_POST["servername"]);
$carriedoutby = trim($_POST["carriedoutby"]);
$workverifiedby = trim($_POST["workverifiedby"]);
$authorisedby = trim($_POST["authorisedby"]);
$workcarriedout = trim($_POST["workcarriedout"]);
$howverified = trim($_POST["howverified"]);
$reason = trim($_POST["reason"]);
$impact = trim($_POST["impact"]);
$rollback = trim($_POST["rollback"]);
try {
$db = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$stmt = $db->prepare("INSERT INTO [dbo].[server_log_entries] (date_time, server_name, carried_out_by, verified_by, authorised_by, work_carried_out, work_verified, change_reason, perceived_impact, rollback_process)
values ('$datetime','$servername','$carriedoutby','$workverifiedby','$authorisedby','$workcarriedout','$howverified','$reason','$impact','$rollback')");
$stmt->execute();
socket_close($socket);
?>
答案 0 :(得分:0)
尝试使用此代码转义单个代码,然后插入db:
$workcarriedout = mysqli_real_escape_string($db, $workcarriedout);
$stmt = $db->prepare("INSERT INTO [dbo].[server_log_entries] (work_carried_out) values ('".$workcarriedout."')");
答案 1 :(得分:0)
字符串中的引号会破坏SQL插入字符串。为避免这种情况,请尝试:
$escaped_string = $db->escape_string($workcarriedout); // does the job with the quotes
$stmt = $db->prepare("INSERT INTO [dbo].[server_log_entries] (work_carried_out)
values ('".$escaped_string."')");
答案 2 :(得分:0)
$stmt = $db->prepare("INSERT INTO [dbo].[server_log_entries] (`work_carried_out`)
values ('\'$workcarriedout\'')");
我测试它现在可以正常工作
有些错误,但我看不清楚,只有你和我的查询之间存在差异
(`date_time`, `server_name` etc..)
这是我的查询,它有效:/
$stmt = $db->prepare("INSERT INTO zeljka (`name`,`lastName`) VALUES ('\'$st\'', '\'$sta\''); and it works :////
答案 3 :(得分:-1)
您可以这样使用:
$stmt = $db->prepare("INSERT INTO [dbo].[server_log_entries] (work_carried_out)
values ('$workcarriedout')");