0

I have a database that is allready setup and can not be changed due to ERP software running on it. When trying to connect to retrieve some data into a table in PHP, i get the following error:

[SQL Server]Invalid object name 'Lareco Live'

I understand that this is due to the space in the tablename --> [Lareco Live$Lead]

This is my script:

// Establishes the connection
$dbh = sqlsrv_connect($serverName, $connectionOptions);
if ($dbh === false) {
    echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
    exit;
}

$sql = "select No_, Description from [Lareco Live$Lead] with (nolock) "; 
$getResults = sqlsrv_query($dbh, $sql);
if ($getResults === false) { 
    echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
    exit;
}
Zhorov
  • 28,486
  • 6
  • 27
  • 52
Ivan Pudic
  • 71
  • 1
  • 11
  • 2
    Have you tried quoting the name: `['Lareco Live$Lead']`. Also pay attention with the `$` in the name as with double quotes PHP will interpret `$Lead` as a variable. – Noah Boegli Apr 29 '20 at 12:11
  • Maybe you should add quote to the table name like this "table name" or 'table name' or `table name`. Read this https://stackoverflow.com/questions/506826/selecting-a-database-in-mysql-with-spaces-in-its-name – Dominik Wilga Apr 29 '20 at 12:13
  • 4
    just escape $Lead: \$Lead --> $sql = "select No_, Description from [Lareco Live\$Lead] with (nolock) "; – lptr Apr 29 '20 at 12:17
  • Adding to the comment by @lptr, the problem is not the space in the name but the `$` character that needs to be escaped in php. I suggest you use names that conform to [regular identifier naming rules](https://learn.microsoft.com/en-us/sql/relational-databases/databases/database-identifiers) to avoid the need to escape special characters in code and enclose the names is square brackets or double-quotes. – Dan Guzman Apr 29 '20 at 12:31
  • Honestly, I'd consider chnaging the name of your table, `Lareco Live$Lead` is a *really* poor choice for an object name. `LarecoLiveLead` or `Lareco_Live_Lead` would be much better choices, as neither need to be delimit identified. – Thom A Apr 29 '20 at 12:32
  • comment from lptr was correct, escaping solved the issue! thank you so much! – Ivan Pudic Apr 29 '20 at 13:05

0 Answers0