由于单引号,无法将字符串插入数据库

时间:2017-07-11 10:11:34

标签: php sql-server

我正在尝试将此json的内容插入我的数据库。

但是我在Summary上得到null结果,因为文本是这样的:

summary":"One of the oldest cities in the United States, Boston definitely has an \"old city\" feel to it. Home to great architecture and historical buildings, the city is also a great place to visit with younger ones, as it also plays host to LEGOLAND and many more children's attractions."

我认为这是由于单引号和我的PHP查询'{$summary}'

$url = file_get_contents("urlcontent/api.json");
$arr = json_decode($url, true);

for($i=0;$i < count($arr);$i++){

$id         = $arr[$i]['id'];  
$location   = $arr[$i]['location'];
$summary    = $arr[$i]['summary'];   

$query = "INSERT INTO [databasename].[dbo].[table]( id , summary, location)";
$query .= "VALUES ('{$id}', '{$summary}', '{$location}' )";

$update_query = sqlsrv_query($con, $query);

  if(!$update_query){
      die("There was an error" .print_r( sqlsrv_errors($con), true));
                }
}

我尝试用以下方法解决这个问题:

$summary = preg_replace("'", "", $arr[$i]['summary']);
$summary = str_replace("'", "", $arr[$i]['summary']);
REPLACE('{$summary}','''','''') //MSSQL Database command

但仍然无法插入该文本并获得NULL结果。我可以echo它和var_dump并且文字可以,但无法将其插入我的桌子。

我的摘要在我的数据库中为text

是什么方法让它发挥作用?干杯

1 个答案:

答案 0 :(得分:4)

您需要正确转义插入的值或使用预准备语句。

$query = "INSERT INTO [databasename].[dbo].[table]( id , summary, location)";
$query .= "VALUES (?, ?, ?)";

$update_query = sqlsrv_prepare($con, $query, [$arr[$i]['id'], $arr[$i]['location'], $arr[$i]['summary']]);
if (!sqlsrv_execute($update_query)) {
  die("There was an error" .print_r( sqlsrv_errors($con), true));
}