odbc_prepare() - Creating Prepared Statements

Q

How To Create Prepared Statements using odbc_prepare()?

✍: Guest

A

If you have a SQL statement that need to executed repeatedly many times with small changes, you can create a prepared statement object with parameters so it can be executed more efficiently.

There are two functions you need to use prepare and execute a prepared statement object:

$statement_object = odbc_prepare($connection,
   $statement_string);
#- The $statement_string may have parameters represented
#- by "?".

$result_set = odbc_execute($statement_object $array);
#- The $array is used to supply values to parameters 
#- defined in the statement object.

The tutorial PHP script below shows you how to insert 3 rows into a table with a prepared statement object with 2 parameters:

<?php
  $con = odbc_connect('FYI_SQL_SERVER','sa','FYIcenter');

  $sql = "INSERT INTO fyi_rates (id, comment) VALUES (?,?)";
  $statement = odbc_prepare($con, $sql);

  $res = odbc_execute($statement, array(301, "Good"));
  $res = odbc_execute($statement, array(302, "Average"));
  $res = odbc_execute($statement, array(303, "Bad"));

  $sql = "SELECT * FROM fyi_rates WHERE id>300";
  $res = odbc_exec($con, $sql);
  while (odbc_fetch_row($res)) {
     print("   ".odbc_result($res,1));
     print(", ".odbc_result($res,2)."\n");
  }
  odbc_free_result($res);

  odbc_close($con); 
?>

If you this sample script, you will get:

   301, Good
   302, Average
   303, Bad

 

SQL Server FAQs - PHP ODBC Functions - Managing Tables and Data Rows

odbc_columns() - Listing All Columns in a Table

SQL Server FAQs - PHP ODBC Functions - Connection and Query Execution

⇑⇑ SQL Server Connection Tutorials

2023-12-31, 1211🔥, 0💬