【问题标题】:Cannot escape single quotes in PHP无法在 PHP 中转义单引号
【发布时间】:2016-07-30 16:58:04
【问题描述】:

所以,我目前正在尝试将一个变量(带空格的字符串)发布到另一个 php 文件。

该变量包含部分 SQL 请求 WHERE Row = 'something'

如果我在我的变量周围加上单引号,它显然会抛出一个错误,因为它不期望“某事”。但是,如果我使用双引号,则 'something' 周围的单引号也会更改为双引号。我怎样才能发布这个字符串?

function getAJAXlink( $count, $text) {

    if (!empty($this->sqlVariable)) {
      $addVarToLink = ", 'sqlVariable': '".$this->sqlVariable."' ";
    }

    if( $this->contentDiv == '')
        return '<a href="'. $this->anchorClass . ' ' . $this->baseURL . $count . '">'. $text .'</a>';

    $pageCount = $count?$count:0;
    $this->additionalParam = "{ 'page' : $pageCount $addVarToLink}";

    return "<a href=\"javascript:void(0);\" " . $this->anchorClass . "
            onclick=\"$.post('". $this->baseURL."', ". $this->additionalParam .", function(data){
                   $('#". $this->contentDiv . "').html(data); }); return false;\">"
           . $text .'</a>';
}

返回:

function getAJAXlink( $count, $text) {

    if (!empty($this->sqlVariable)) {
      $addVarToLink = ", 'sqlVariable': \"".$this->sqlVariable."\" ";
    }

    if( $this->contentDiv == '')
        return '<a href="'. $this->anchorClass . ' ' . $this->baseURL . $count . '">'. $text .'</a>';

    $pageCount = $count?$count:0;
    $this->additionalParam = "{ 'page' : $pageCount $addVarToLink}";

    return "<a href=\"javascript:void(0);\" " . $this->anchorClass . "
            onclick=\"$.post('". $this->baseURL."', ". $this->additionalParam .", function(data){
                   $('#". $this->contentDiv . "').html(data); }); return false;\">"
           . $text .'</a>';
}

返回:

【问题讨论】:

  • 一行代码上混合四种语言只是在乞求字符串引用问题。你肯定能以某种方式将它们分开吗?
  • 尝试使用php HEREDOC
  • 你应该用双引号引起来,忘记使用单引号。我发现这在使用 html 时很有帮助。

标签: javascript php html mysql post


【解决方案1】:

自己找到了答案。这是工作代码:

function getAJAXlink( $count, $text) {

    if (!empty($this->sqlVariable)) {
      $addVarToLink = ", 'sqlVariable': &quot;".$this->sqlVariable."&quot; ";
    }

    if( $this->contentDiv == '')
        return '<a href="'. $this->anchorClass . ' ' . $this->baseURL . $count . '">'. $text .'</a>';

    $pageCount = $count?$count:0;
    $this->additionalParam = "{ 'page' : $pageCount $addVarToLink}";

    return "<a href=\"javascript:void(0);\" " . $this->anchorClass . "
            onclick=\"$.post('". $this->baseURL."', ". $this->additionalParam .", function(data){
                   $('#". $this->contentDiv . "').html(data); }); return false;\">"
           . $text .'</a>';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多