如何使用 SQLSRV 准备语句将数据插入 sql

How to insert data to sql using SQLSRV Prepared statement

我已尽一切努力让这段代码正常工作,但我真的被困住了。据我所知,一切都应该如此。我可能会遗漏一些非常容易但我找不到的东西。任何帮助,将不胜感激。

session_start();
date_default_timezone_set('europe/london');
ini_set('display_errors', 1); error_reporting(-1);

require 'connect.php';
if(isset($_POST['submit'])){


    $cutdate = $_POST['start_date'];
    $split = explode(" ",$cutdate); 
    $dateformat = $split[0];
    $date = str_replace("/", "-", $dateformat);
    $dayofweek = date_format(new DateTime($date),'l');
    $monthofyear = date_format(new DateTime($date),'F');
    $yearof = date_format(new DateTime($date),'Y');
    $weekcommencingform = Date('d-m-Y', strtotime('monday this week', strtotime($date)));
    $weekcommencing = str_replace("-", "/", $weekcommencingform);

    $inc = $_POST['inc'];
    $status = 'Open';
    $start = $_POST['start_date'];
    $incday = $dayofweek;
    $incweek = $weekcommencing;
    $incmonth = $monthofyear;
    $incyear = $yearof;
    $channel = $_POST['channel'];
    $journey = $_POST['journey'];
    $application = $_POST['application'];
    $category = $_POST['category'];
    $priority = $_POST['priority'];
    $description = $_POST['description'];
    $opened_by = $_SESSION["user"];

    $sql = "INSERT INTO [dbo].[incidents] 
                        (inc, status, act_start_date, start_date, 
                        inc_day, inc_week, inc_month, inc_year, 
                        opened_by, priority, system, category, 
                        channel, journey, description) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $params = array( &$inc, &$status, &$start, &$start, 
                    &$incday, &$incweek, &$incmonth, &$incyear, 
                    &$opened_by, &$priority, &$application, &$category, 
                    &$channel, &$journey, &$description);

    $stmt = sqlsrv_query($con, $sql, $params);

if ($stmt) {  
    echo "Row successfully inserted";  
} else {  
    echo "Row insertion failed";  
    die(print_r(sqlsrv_errors(), true));  
}  

函数sqlsrv_query没有准备,它只是发送SQL立即执行。它不支持准备好的语句,因此您必须内联包含经过清理的数据。要使用准备好的语句,您必须修复代码并更改

$stmt = sqlsrv_query($con, $sql, $params);
if ($stmt) {  
    echo "Row successfully inserted";  
} else {  
    echo "Row insertion failed";  
    die(print_r(sqlsrv_errors(), true));  
}

$stmt = sqlsrv_prepare($con, $sql, $params);
if (sqlsrv_execute( $stmt ) === false) {
    echo "Row insertion failed";  
    die(print_r(sqlsrv_errors(), true)); 
} else echo "Row successfully inserted"; 

这是 sqlsrv_query and sqlsrv_prepare

的文档