SQL in php script

0
SELECT
CAST(REPLACE(CAST(DsXML as Nvarchar(Max)),' xmlns="http://www.portalfiscal.inf.br/nfe"','') as xml).value('(/nfeProc/NFe/infNFe/transp/vol/qVol/node())[1]', 'int') as [qVol]
FROM SPDNFE
WHERE CdIdNFe = 'NFe13161203976141000132550030000435291400513027'

By this SQL query within a php script, I get the following error.

Parse error: syntax error, unexpected 'xmlns' (T_STRING)

As it is in PHP.

public function teste($teste) {
    $sql = 'SELECT
        CAST(REPLACE(CAST(DsXML as Nvarchar(Max)),' xmlns="http://www.portalfiscal.inf.br/nfe"','') as xml).value('(/nfeProc/NFe/infNFe/transp/vol/qVol/node())[1]', 'int') as [qVol]
        FROM SPDNFE
        WHERE CdIdNFe = '$teste'';
    $results = array();
    $stmt = $this->conn->prepare($sql);
    $stmt->execute();
    if ($stmt) {
        while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
            $info = new Model();
            $info->getQVol($row->qVol);
            $results[] = $info;
        }
    }
    return $results;
}
    
asked by anonymous 08.08.2017 / 14:39

1 answer

1

Use the escaping of the apostrophes:

$sql = "SELECT
        CAST(REPLACE(CAST(DsXML as Nvarchar(Max)),' xmlns=\"http://www.portalfiscal.inf.br/nfe\"','') as xml).value('(/nfeProc/NFe/infNFe/transp/vol/qVol/node())[1]', 'int') as [qVol]
        FROM SPDNFE
        WHERE CdIdNFe = \'$teste\'";

@edit

When you use the apostrophe to delimit your string , what you tried to do is interpreted as follows and delimited in the following part:

$sql =  'SELECT CAST(REPLACE(CAST(DsXML as Nvarchar(Max)),' 

You started string with ' and then there is an occurrence of ' where it should not mean the limit of string .

As you want string to contain the literal, you should escape it.

See a similar example where the same error occurs:

$string = 'Santa Bárbara D'Oeste';

For the ' pends to function correctly in string , use \ to escape, or a function such as addslashes :

$string = 'Santa Bárbara D\'Oeste';

$string = addslashes('Santa Bárbara D'Oeste');

I suggest you read strings .

    
08.08.2017 / 14:47