PHP
  Home arrow PHP arrow Page 4 - Executing SQL Server Stored Procedures Wit...
Moblin
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Actuate Whitepapers 
Moblin 
JMSL Numerical Library 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Executing SQL Server Stored Procedures With PHP
By: Joe O'Donnell
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 53
    2003-01-01

    Table of Contents:
  • Executing SQL Server Stored Procedures With PHP
  • Configuring PHP
  • Running the mssql_xxx functions
  • Executing stored procedures
  • Capturing output parameters and return values
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
    Try It Free
     
    ADVERTISEMENT

    Be the architects of evolution and help create the mobile internet future. It’s your move---enter to win here!

    Executing SQL Server Stored Procedures With PHP - Executing stored procedures


    (Page 4 of 6 )

    Executing a stored procedure with PHP and the mssql_xxx set of functions is easy. To execute a stored procdure that accepts no parameters and doesn't return a value, we only need to make use of the mssql_init and mssql_execute functions.

    Open query analyzer on your SQL Server and run the following code:

    USE Northwind

    GO

    CREATE PROC sp_AddNewShipper

    AS

    -- Add a record to the shippers table

    INSERT INTO Shippers(CompanyName, Phone)

    VALUES('Johns Shipping', '(555) 555-0493')


    We've just created a new stored procedure that's attached to the Northwind database. It's called sp_AddNewShipper. When it is executed, it will add a new record to the shippers table and won't return a value.

    To execute sp_AddNewShipper from PHP, create a new file called shipper.php and enter the following code into it:

    <?php

    $myServer = "localhost";

    $myUser = "sa";

    $myPass = "";

    $myDB = "Northwind";

    $s = @mssql_connect($myServer, $myUser, $myPass)

    or die("Couldn't connect to SQL Server on $myServer");

    $d = @mssql_select_db($myDB, $s)

    or die("Couldn't open database $myDB");

    $query = mssql_init("sp_AddNewShipper", $s);

    $result = mssql_execute($query);

    ?>


    When you run the script in your web browser and then check the shippers table of your Northwind database, you'll see that we've just added a new record:

    Our new record in the shippers table

    The only new parts of our code are the calls to mssql_init and mssql_execute:

    $query = mssql_init("sp_AddNewShipper", $s);

    $result = mssql_execute($query);


    The call to mssql_init initializes our call to the sp_AddNewShipper stored procedure. It's main use is to facilitate the addition of output parameters for stored procedure calls (which we will look at next), and its signature looks like this:

    int mssql_init ( string sp_name [, int conn_id])

    It accepts the name of the stored procedure as well as an optional connection identifier, which we've passed in as $s. It returns a numerical identifier that we then pass to mssql_execute. Mssql_execute actually creates all of the necessary SQL plumbing and executes our stored procedure on the SQL Server. Its signature looks like this:

    int mssql_execute ( int stmt)

    Nothing to really explain about the mssql_execute function except that it takes the identifier of the statement to execute (which is returned by a call to mssql_init) and returns a result that can optionally include one/more records.

    It's good to be able to execute stored procedures that don't accept or return any parameters, but in the real world stored procedures usually accept and/or return both parameters and values.

    Clear your query analyzer window and enter the following batch of TSQL code:

    USE Northwind

    GO

    CREATE PROC sp_GetProductsBySupplier

    @supplierId TINYINT

    AS

    -- Return products whose supplierId field is @supplierId

    SELECT ProductName

    FROM Products

    WHERE SupplierID = @supplierId

    ORDER BY ProductName ASC


    We've just created a stored procedure called sp_GetProductsBySupplier. It accepts one integer input parameter called SupplerID, which will be used to return all products from the Northwind products table based on that products SupplierID field.

    We can now use PHP and the mssql_xxx functions to execute our stored procedure, passing in an input parameter that contains an integer value (which will be used to filter the products based on their SupplierID field). Create a new file called products.php and enter the following code into it:

    <?php

    $myServer = "localhost";

    $myUser = "sa";

    $myPass = "";

    $myDB = "Northwind";

    $s = @mssql_connect($myServer, $myUser, $myPass)

    or die("Couldn't connect to SQL Server on $myServer");

    $d = @mssql_select_db($myDB, $s)

    or die("Couldn't open database $myDB");

    $query = mssql_init("sp_GetProductsBySupplier", $s);

    $supId = 2;

    mssql_bind($query, "@supplierId", &$supId, SQLINT2);

    $result = mssql_execute($query);

    $numProds = mssql_num_rows($result);

    echo "<h1>" . $numProds . " Product" . ($numProds == 0 ? "" : "s") . " Found: </h1>";

    while($row = mssql_fetch_row($result))

    {

    echo "<li>" . $row[0] . "</li>";

    }

    ?>


    Here's a screen shot of the output from products.php:

    Running our sp_GetProductsBySupplier stored procedure

    We can also run our stored procedure using query analyzer with the following code:

    USE Northwind

    GO

    EXEC sp_GetProductsBySupplier 2


    ... which produces the following output in query analyzer:

    Running our stored proc in query analyzer

    The only new mssql function that we're calling in products.php is mssql_bind, which we can use to create a new input/output parameter for our stored procedure. Its signature looks like this:

    int mssql_bind ( int stmt, string param_name, mixed var, int type [, int is_output [, int is_null [, int maxlen]]])

    In our example we want to pass in one numerical input parameter, so we use mssql_bind like this:

    mssql_bind($query, "@supplierId", $supId, SQLINT2);

    For the type parameter, I've specified SQLINT2, which is defined by PHP internally to represent an integer of two bytes. Other possible values for the type parameter include SQLTEXT, SQLVARCHAR, SQLCHAR, SQLINT1, SQLINT2, SQLINT4, SQLBIT and SQLFLT8.

    I haven't specified a value for the is_output, is_null and maxlen parameters. If I wanted to, I could've specified FALSE for is_output, meaning that our parameter is an input parameter and not an output parameter (is_output defaults to false anyway, so I chose not to specify it).

    Once we've bound our parameter to our stored procedure, we execute the stored procedure using mssql_execute, capturing its recordset into a variable called $result:

    $result = mssql_execute($query);

    More PHP Articles
    More By Joe O'Donnell


     

    PHP ARTICLES

    - Making Usage Statistics in PHP
    - Installing PHP under Windows: Further Config...
    - File Version Management in PHP
    - Statistical View of Data in a Clustered Bar ...
    - Creating a Multi-File Upload Script in PHP
    - Executing Microsoft SQL Server Stored Proced...
    - Code 10x More Efficiently Using Data Access ...
    - A Few Tips for Speeding Up PHP Code
    - The Modular Web Page
    - Quick E-Commerce with PHP and PayPal
    - Regression Testing With JMeter
    - Building an Iterator with PHP
    - PHP Frontend to ImageMagick
    - Using PEAR's mimeDecode Module
    - Incoming Mail and PHP






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway