Sending SQL to MSSQL
The function mssql_query() sends an SQL statement to the MSSQL/MSDE installation. Again, the parameter order is a bit strange: first the SQL command, then the database handle. However, as you saw in Listing 7.18 in the call to mssql_select_db(), this information can also be omittedthen, the last connection established is used automatically.
Another important point is escaping special characters. In MSSQL/MSDE, single quotes must not be escaped using a backslash, but double quotes are the way to go:
INSERT INTO quotes (quote, author, year) VALUES ('Ain''t Misbehavin''', 'Louis Armstrong',
1929)
To achieve this, addslashes() can be usedhowever, first, it has to be configured to behave so that MSSQL/MSDE-compatible strings are returned:
Sending SQL to MSSQL/MSDE (mssql_execute.php; excerpt)
ini_set('magic_quotes_sybase', 'On');
$author = addslashes($_POST['author']);
<?php
if ($db = @mssql_connect('localhost', 'user',
'password')) {
require_once 'stripFormSlashes.inc.php';
mssql_select_db('phrasebook', $db);
ini_set('magic_quotes_sybase', 'On');
mssql_query(sprintf(
'INSERT INTO quotes (quote, author, year)
VALUES (\'%s\', \'%s\', \'%s\')',
addslashes($_POST['quote']),
addslashes($_POST['author']),
intval($_POST['year'])), $db);
echo 'Quote saved.';
mssql_close($db);
} else {
echo 'Connection failed.';
}
?>
The listing at the beginning of this phrase sanitizes some form data and writes it to the (by now) well-known sample database.
|