1

I have functions stored in SQL table that I need to use inside JS. The problem is, that I also need to use PHP variables in these functions.

The following:

<?php
  $container='11';
  $title='Header';
  $function_text =
  <<<EOT
    $(function() {
      $('#container$container').parent('div').find('h3').html('$title');
    });
  EOT;
  echo $function_text;
?>

returns correctly:

$(function() {
  $('#container11').parent('div').find('h3').html('Header');
});

but this one:

<?php
  $ID=1;
  $container='11';
  $title='Header';
  $article = $cls -> Query(sprintf('SELECT * from graphs WHERE ID="%s"', $ID));
  $function_text = $article[0]['function'];
  echo $function_text;
?>

prints exactly the contents of SQL field, without recognising variables:

$(function() {
  $('#container$container').parent('div').find('h3').html('$title');
});

How could I get the variables to be injected to echoed text?

4

1 回答 1

1
  1. 更改存储在数据库中的数据,以便它使用格式占位符而不是对变量的引用:

    $(function() {
      $('#container%s').parent('div').find('h3').html('%s');
    });
    
  2. 使用sprintf()

    $function_text = sprintf($article[0]['function'], $container, $title);
    
于 2013-10-20T18:58:29.940 回答