variables in a sql statement
Moderator: General Moderators
variables in a sql statement
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.
- social_experiment
- DevNet Master
- Posts: 2793
- Joined: Sun Feb 15, 2009 11:08 am
- Location: .za
Re: variables in a sql statement
Code: Select all
<?php
$variable = 'A Girl';
$pagename = 'Index';
//
echo 'Hello ' . $variable . ' this is ' . $pagename;
?>“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
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: variables in a sql statement
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)
Re: variables in a sql statement
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.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 );