Page 1 of 1
variables in a sql statement
Posted: Mon Oct 31, 2011 6:41 pm
by danwguy
So here is my problem, I am writing a program and they want to have variables that get replaced in different versions of a script, so say in my mssql table it is "Hello, $fullname, this is $agentname" when output to the page it shows exactly like that "Hello, $fullname, this is $agentname" even if I define $fullname = "A Girl"; before I echo the content returned from the db. How would I go about replacing those vars with what I define? I hope that's clear, Thank you for your help in advance.
Re: variables in a sql statement
Posted: Mon Oct 31, 2011 11:41 pm
by social_experiment
Code: Select all
<?php
$variable = 'A Girl';
$pagename = 'Index';
//
echo 'Hello ' . $variable . ' this is ' . $pagename;
?>
The above should output the values within the variables
Re: variables in a sql statement
Posted: Tue Nov 01, 2011 2:13 am
by Christopher
Instead of storing "Hello, $fullname, this is $agentname" in the database, store a template with tags in it, something like "Hello, {fullname}, this is {agentname}". The in the code do something like this:
Code: Select all
$fromdatabase = "Hello, {fullname}, this is {agentname}";
$variable = 'Mary';
$agentname = 'Fred';
echo str_replace(array('{fullname}', '{agentname}'), array($variable, $agentname), $fromdatabase );
Re: variables in a sql statement
Posted: Tue Nov 01, 2011 11:24 am
by danwguy
Christopher wrote:Instead of storing "Hello, $fullname, this is $agentname" in the database, store a template with tags in it, something like "Hello, {fullname}, this is {agentname}". The in the code do something like this:
Code: Select all
$fromdatabase = "Hello, {fullname}, this is {agentname}";
$variable = 'Mary';
$agentname = 'Fred';
echo str_replace(array('{fullname}', '{agentname}'), array($variable, $agentname), $fromdatabase );
That's what I was looking for, I didn't know if a str_replace would be the right way to go or not, plus I've never used array with it before. Thank you.