How can I do something like this?

I’m trying to place these in a seperate file that’ll be included on every page.

[php]
$sql = ‘select id, name, age, address, pincode from json where name = :name’;
$arr = array(":name" => $name);
// There are some 30 diff sql’s and arrays[/php]

Another page

[php]
$name = ‘peter’;
$conn = connect();

function myType(){
global $conn;
global $sql; 
global $arr; 
$stmt = $conn->prepare($sql);
$stmt->execute($arr);

while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
      foreach ($row as $value) {
      echo $value.' <br>';
      }
   }
}

myType();
[/php]

What I’m trying to do is keep the sql’s and arrays in a separate file and use them when needed.

Keeps things clean and easy to maintain. But the variables are declared later, which gives me: Notice: Undefined variable: name in C:\web\apache\htdocs\dev\json.php on line 24

Can you see a way to do this without uglying things?

Thanks,

You just need to read some more articles about PHP variable’s scope.

http://php.net/manual/en/language.variables.scope.php

If you mean you want “CODE” that is placed on many pages, you just use the “include” command.
You create a file with that data in it and place the “include” wherever you want that file to be placed.

If you mean you want “DATA” placed on many pages, you can pull the data at the beginning of your program and then save it as a SESSION variable to be used on other pages or write the data into a file and read it back into the other pages.

Or, since you are talking about queries, why not just save the arrays and sql’s inside a DB table.
You could save all you want and just query it to pull it out and fill in the info needed. Just replace the :name in your query results with the name that is needed. Shouldn’t be to hard. It would not be very ugly as you already have DB code and just need an extra query to set it all up.

Hmmm, did that make sense? Good luck!

Sponsor our Newsletter | Privacy Policy | Terms of Service