简体   繁体   中英

Passing PHP String as SQL Command and Preserving Line Breaks

I am trying to run a SQL stored procedure , and am passing the execution command to the server using PHP's PDO class . Here's my script as it stands now:

$db = new PDO("dblib:dbname=databaseName;host=hostName", databaseUser, databasePassword);
$query = "
    USE [thisDatabase]
    GO
    DECLARE @return_value int
    EXEC    @return_value = [dbo].[thisSproc]
            @State = 'GA',
            @Type = 'Counseling',
            @PVCampusVueCode = NULL
    SELECT  'Return Value' = @return_value
    GO";
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

Note that that query, when run directly on the database itself, returns results correctly without error.

However, when I run it using my PHP script and I parse the result, I get a syntax error near the word 'GO' (SQL error 102). This turns out to be because the command is being passed to the SQL server as a single line, without line breaks . So, it ends up looking like this:

USE [thisDatabase] GO DECLARE @return_value int EXEC @return_value = [dbo].[thisSproc] @State = 'GA', @Type = 'Counseling', @PVCampusVueCode = NULL SELECT 'Return Value' = @return_value GO

This is a problem, because obviously the 'GO' command has to be on it's own line.

I have looked around for a fix to this, and can't find one. How do I either preserve the line breaks so the query executes correctly, or solve the problem some other way?

只需将查询作为单独的query()调用运行即可。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM