I'm trying to set up a function that will get me a mysql select from database as I will be using this query a few times. So I thought instead of writing the same select code in each php file I could put it into a function and call it when I want. So far I'm using this in different files to get results from the database:
$stmt_query = $db->prepare("SELECT * FROM table1 WHERE memberID='$id_memberID'");
$stmt_query->execute();
$row_query = $stmt_query->fetchAll(PDO::FETCH_ASSOC);
foreach ($row_query as $show_query) {
$id = $show_query['id'];
$model = $show_query['model'];
$year = $show_query['year'];
}
And then
echo $id; echo $model; echo $year;
The question is how can I achieve the same without doing the above multiple times in each different php file?
Write a function like you suggested, just declare your $db
var as a global since php limits function scope to just the function.
function getAll($id_memberID) {
global $db;
// your code
}
Call this function in your code...
function query_fetch(){
$stmt_query = $db->query("SELECT * FROM table1 WHERE memberID='$id_memberID'");
$row=$stml_query->fetch();
return $row;
}
Then you can get data by simply using it in while loop.
function query_fetch();
while($row){
$id = $row['id'];
$model = $row['model'];
$year = $row['year'];
}
Or you can use foreach
as you have used.
And this is also not much...you can repeat if you want..
$stmt_query = $db->query("SELECT * FROM table1 WHERE memberID='$id_memberID'");
while($row=$stml_query->fetch()){
$id = $row['id'];
$model = $row['model'];
$year = $row['year'];
}
I would stay away from using globals. globals are worse than singletons which are worse than dependency injection (DI). If you have the ability, go to DI using a dependency injection container right away. This article gives a basic example of how to use DI http://paul-m-jones.com/archives/6014 You would basically set up a bootstrap script for your application, declare the DI container, create your connection, add the connection to the container and then fetch it out of the container and pass it as a parameter to any methods that need it. There are a bunch of easy to setup and use PHP DI containers. PHP-DI and Pimple are two good examples.