简体   繁体   中英

How to correctly sanitize mssql query that stores emails

I have a query that goes to a mailbox and tries to save all emails in a table. It works in most cases but it fails when the email content value has double or single quote marks. How would I modify my code to correctly insert all queries?

    $num = imap_num_msg($imap);
    if($num > 0)
    {
        for($b = $num; $b > 0; $b--)
        {
            $body = $this->get_part($imap, $b, "TEXT/HTML");
            if($body == "")
            {
                $body = $this->get_part($imap, $b, "TEXT/PLAIN");
            }
            $header = imap_headerinfo($imap, $b);
            $subject = $header->subject;
            $fromaddress = $header->fromaddress;
            $body = str_replace("'", "''", $body);
            //$body = str_replace("\"", "\"\"", $body);
            $sql3 = "INSERT INTO [tbl_test] (content) 
                    VALUES ('".$body."')";
            $result3 = mssql_query($sql3, $dbh1);
        }
    }

Afterwords I get these errors:

Warning: mssql_query(): message: Unclosed quotation mark after the character string 'Please investigate why the below s....

Warning: mssql_query(): General SQL Server error: Check messages from the SQL Server (severity 15) in /var/www/testing.php on line 38

You want to be using parameters:

$query = "INSERT INTO test (email, body) VALUES (?,?);";
$arrParams[]="my@domain.com";
$arrParams[]="My email body has quotes\'s or double quotes \" in it.";
$resource=sqlsrv_query($conn, $query, $arrParams); 

Source: sqlsrv_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