Add parameters to a PHP mssql query

前端 未结 3 1404
轮回少年
轮回少年 2021-01-15 05:00

Given the following query (in the code, NOT a stored procedure); how can I add parameters to the query rather than including the condition values directly in the query? In o

相关标签:
3条回答
  • 2021-01-15 05:32

    What you need is a prepared statement (or just a DAL that will allow you to parameterise your queries!).. One option is to use PDO, specifically with the PDO_SQLSRV driver..

    When doing this you can prepare your queries in a parameterised form, and pass them in at query time, for example..

    $conn = new PDO("sqlsrv:Server=$myServer;Database=$myDB", $myUser, $myPass);
    $stmt = $conn->prepare('SELECT lastname,firstname,address,phone,email FROM person WHERE lastname LIKE ?');
    $stmt->execute(array($lastname));
    $result = $stmt->fetchAll();
    foreach ($result as $row) {
        ...
    

    (note code above should be in an in-place replacement, however it's untested!)

    If you have a lot of parameters in your query at some point, it may be best to use named parameters so that you can keep track of them better.

    0 讨论(0)
  • 2021-01-15 05:33

    First of all abandon the outdated extension and use sqlsrv instead:

    These functions allow you to access MS SQL Server database.

    This extension is not available anymore on Windows with PHP 5.3 or later.

    SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

    After that you get suppport for prepared statements:

    $dbh = sqlsrv_connect ($serverName, $credentials);
    $stmt = sqlsrv_prepare($dbh, 'SELECT lastname,firstname,address,phone,email FROM person WHERE lastname LIKE ?', array(&$lastName));
    
    
    if(sqlsrv_execute($stmt))
    {
       while(false !== ($row = sqlsrv_fetch_array($stmt)){
         // do stuff with $row
       }
    }
    

    Of course if i were i would just use PDO as others have suggested with presents the same interface to all db the extensions it supports.

    If youre stuck using mssql for some reason then i believe youre also stuck manually escaping all your query parameters.

    0 讨论(0)
  • 2021-01-15 05:43

    Use PDO to make it secure

    http://php.net/manual/en/book.pdo.php

    0 讨论(0)
提交回复
热议问题