如何使用SQLSRV Prepared语句向sql插入数据

时间:2018-03-29 19:16:48

标签: php insert sqlsrv

我已经尝试了一切来使这段代码工作,我真的被卡住了。据我所知,一切都应该如此。我可能会遗漏一些非常简单的东西,但我找不到它。任何帮助,将不胜感激。

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));  
}  

1 个答案:

答案 0 :(得分:2)

函数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

的文档页面