簡體   English   中英

如何使用 SQLSRV Prepared 語句向 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_querysqlsrv_prepare 的文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM