dongxiaoxiao1983 2012-02-07 23:06
浏览 82
已采纳

PHP:从mysql查询中替换“变量”(表的内容)

I am trying to echo a variable, from a mysql query, like this:

<?php
...//FYI: mysql connection already established
//Table: title 
//col: page | title
//row: html | "$domain_name: Welcome"

$page_id = basename(getcwd());
$domain_name = "Name of My Domain";

$sql = "SELECT title FROM mydatabase.title WHERE page = '$page_id' ";
//The query's result is 1 row
$dbq = mysql_query ($sql);
$dba = mysql_fetch_array( $dbq );
echo $dba["title"];
//it outputs: $domain_name: Welcome", instead of "Name of My Domain: Welcome"
?>

What am I doing wrong? I am trying to replace the "variable [$domain_name] in the table's content for it's php value. -I thought " (double quotes) are supposed to replace the variable with it's value.

PS. I am a beginner

EDIT 2/7/2012, 3:14pm: Forgot to mention. The query works OK. $dba['title'] has "$domain_name: Welcome" as a value. The problem is, it is not replacing $domain_name

  • 写回答

2条回答 默认 最新

  • dqbjvg2518 2012-02-07 23:10
    关注

    I thought " (double quotes) are supposed to replace the variable with it's value.

    That works only in case when you specify the string in your code. If the string comes from outside - it doesn't have such magic behaviour.

    So the only solution you could go with is:

    echo str_replace('$domain_name', $domain_name, $dba["title"]);
    

    Or you could go with some sort of template engine like Twig or Smarty and treat your database value as a template, and your variables as the data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画