mssql_query() - Executing SQL Statements

Q

How To Execute a SQL Statement using mssql_query()?

✍: Guest

A

Once you have created a connection object, you can use the mssql_query() function to send a SQL statement to the SQL Server linked to the connection object for execution.

Here is a simple PHP script that creates a new schema and a new table:

<?php
  $con = mssql_connect('LOCALHOST','sa','FYIcenter');
  mssql_select_db('FyiCenterData', $con);

  # creating a new schema
  $sql = 'CREATE SCHEMA fyi';
  mssql_query($sql, $con);
  
  # creating a new table
  $sql = 'CREATE TABLE fyi.center (name VARCHAR(80))';
  mssql_query($sql, $con);

  mssql_close($con); 
?>

If you run this script for the first time, it will execute those two statements correctly for you. But if you run it again, you will some warning messages:

Warning: mssql_query(): message: There is already an object 
named 'fyi' in the database. (severity 16) 
in C:\test\fyi-center.php on line 7

Warning: mssql_query(): message: CREATE SCHEMA failed 
due to previous errors. (severity 16) 
in C:\test\fyi-center.php on line 7

The messages are very clear and easy to understand.

 

mssql_get_last_message() - Retrieving Error Messages

mssql_select_db() - Selecting an Exiting Database

SQL Server FAQs - PHP MSSQL Functions - Connections and Query Execution

⇑⇑ SQL Server Connection Tutorials

2024-04-07, 1297🔥, 0💬