Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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

share|improve this question
up vote 2 down vote accepted

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.

share|improve this answer

You can replace it on database level:

$sql = 'SELECT REPLACE(title, \'$domain_name\',\''.$domain_name.'\') as title FROM mydatabase.title WHERE page = '.intval($page_id);
//The query's result is 1 row
$dbq = mysql_query ($sql);
$dba = mysql_fetch_array( $dbq );
echo $dba["title"];

(Note the single quotes)

share|improve this answer
    
Your eval code won't work – zerkms Feb 7 '12 at 23:19
    
@zerkms: I see, as it's not complete code.. – konsolenfreddy Feb 7 '12 at 23:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.