monkeyman monkeyman - 7 months ago 10
SQL Question

How do I do multiple string replacements in multiple queries?

I have an array called

$queries
that looks like this:

Array (
[0] => SELECT * FROM StudentRecord WHERE Year = '%YEAR%' AND Session = '%SESSION%' AND StudentID = '%SID%';
[1] => SELECT * FROM Student_ApplicationRecord WHERE ApplicationYear = '%YEAR%' AND Session%SESSION% = 1;
)


I also have a second array called
$variables
that looks like this:

$variables = array('YEAR' => 2016, 'SESSION' => 1, 'SID' => $_SESSION['sid']);


I want to replace the variables in
$queries
with the correct values in
$variables
.

I have tried many solutions and the best I've come up with so far is:

foreach ($queries as $query)
foreach($variables as $key=>$value)
$newqueries[] = str_replace("%".$key."%", $value, $query);


However this is only replacing one variable at a time in each query.

i.e. when I do:

foreach ($newqueries as $query)
print ($query);


The result for each query is:

SELECT * FROM StudentRecord
WHERE Year = '%YEAR%' AND Session = '%SESSION%' AND SID = '%SID%';

SELECT * FROM StudentRecord
WHERE Year = '%YEAR%' AND Session = '1' AND SID = '%SID%';

SELECT * FROM StudentRecord
WHERE Year = '%YEAR%' AND Session = '%SESSION%' AND SID = '1234';


What I want is a final array
$newqueries
that looks like this:

Array (
[0] => SELECT * FROM StudentRecord WHERE Year = '2016' AND Session = '1' AND StudentID = '1234';
[1] => SELECT * FROM Student_ApplicationRecord WHERE ApplicationYear = '2016' AND Session1 = 1;
)


Can anyone help me out please? I apologise if this has been asked before but I have not been able to find any similar questions.

Answer

Since str_replace() accepts arrays for the $search and $replace arguments you could use that.

$search = ['%YEAR%', '%SESSION%', '%SID%'];
$replace = ['2016', '1', $_SESSION['id']];
$newQueries = [];
foreach ($queries as $query) {
    $newQueries[] = str_replace($search, $replace, $query);
}