variables in a sql statement

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
danwguy
Forum Contributor
Posts: 256
Joined: Wed Nov 17, 2010 1:09 pm
Location: San Diego, CA

variables in a sql statement

Post 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.
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: variables in a sql statement

Post 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
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: variables in a sql statement

Post 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 );
(#10850)
danwguy
Forum Contributor
Posts: 256
Joined: Wed Nov 17, 2010 1:09 pm
Location: San Diego, CA

Re: variables in a sql statement

Post 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.
Post Reply