SQL Server is a common database management system for many websites and applications. In PHP programming, operating a SQL Server database is a necessary skill. This article will introduce some common SQL Server database operations.
In PHP, to connect to SQL Server database, you need to use the mssql_connect() function. The following is a sample code to connect to a SQL Server database:
$serverName = "localhostSQLEXPRESS"; $connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password"); $conn = sqlsrv_connect( $serverName, $connectionInfo);
Once the connection is successful, you can query the database. A common query method is to use the mssql_query() function. The following is sample code for querying a SQL Server database:
$query = "SELECT * FROM tableName"; $result = mssql_query($query, $conn); while ($row = mssql_fetch_array($result)) { echo $row['columnName']; }
Inserting data is a common operation to add new data to the database. The following is a sample code for inserting data into a SQL Server database:
$query = "INSERT INTO tableName (columnName1, columnName2) VALUES ('value1', 'value2')"; mssql_query($query, $conn);
When you need to update existing data in the database, you can use the UPDATE statement. The following is a sample code to update data in a SQL Server database:
$query = "UPDATE tableName SET columnName1='value1', columnName2='value2' WHERE id='1'"; mssql_query($query, $conn);
Deleting data from the database is also a common operation. The following is a sample code to delete data in a SQL Server database:
$query = "DELETE FROM tableName WHERE id='1'"; mssql_query($query, $conn);
When you need to get data from multiple tables, you can use the JOIN statement . The following is sample code for querying multiple tables in a SQL Server database:
$query = "SELECT tableName1.columnName1, tableName2.columnName2 FROM tableName1 JOIN tableName2 ON tableName1.id = tableName2.id"; $result = mssql_query($query, $conn); while ($row = mssql_fetch_array($result)) { echo $row['columnName1'] . " " . $row['columnName2']; }
Summary
SQL Server is one of the most common databases used in PHP programming. In this article, we introduce some common SQL Server database operations, including connecting to SQL Server database, querying SQL Server database, inserting data, updating data, deleting data and querying multiple tables. These operations will be very useful when writing your next PHP project.
The above is the detailed content of What are the common SQL Server database operations in PHP programming?. For more information, please follow other related articles on the PHP Chinese website!