<?php
$serverName = "(local)"; //serverName
$connectionInfo = array( "Database"=>"DabaseNew", "UID"=>"sa", "PWD"=>"*****");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn==true ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM Dbo.DATABASE COMPANY SERVICES$Employee";
$stmt = sqlsrv_query( $conn, $sql);
if(!$stmt){
die( print_r( sqlsrv_errors(), true));
}
$rows = sqlsrv_has_rows($stmt);
while($obj = sqlsrv_fetch_object( $stmt)){
echo $obj->Description.", ".$obj->lName."<br />";
}
?>
I am trying to connect to php to my sql server using sqlsrv_connect. The above code gives me an error below;
Output: Connection established. Array ( [0] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 102 [code] => 102 [2] => [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near 'SERVICES'. [message] => [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near 'SERVICES'. ) )
You need to escape the $
character with \$
, as php treats it as first character ov a variable. Try this:
$sql = "SELECT * FROM Dbo.[DATABASE COMPANY SERVICES\$Employee]";
EDIT:
To avoid escapingg you could also use single quotes '
instead of double quotes "
. Then PHP does not resolve variables within the string. (see this question)
$sql = 'SELECT * FROM Dbo.[DATABASE COMPANY SERVICES$Employee]';
2nd EDIT:
To concatenate two strings use .
operator like this:
$foo = "Hello ";
$bar = $foo."world!"; // gives "Hello world!"
As you can read within the answer linked within the first edit "
double quotes resolve variables inbetween, while '
single quotes don't. your possible solution could be like this:
$query = 'SELECT [First Name] AS firstName, [Last Name] AS lastName
FROM Dbo.[DATABASE COMPANY SERVICES$Employee]
WHERE [Employee Number] = 15 OR [E-Mail] = \''.mssql_escape($mail).'\'';
But you should NEVER directly send a GET parameter top your sql server. Anybody could infiltrate your database or even delete it. Therefore you should add a escape function like this one or consider using another db-library like PDO and build parameterized queries. It might me sufficient to escape single quotes within the variable with another single quote like this:
function mssql_escape($str) {
return str_replace("'", "''", $str);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments