plainhat;10937066 wrote:What I find is that I'm writing the same queries over and over again. There's a part of me that wants to put these all in one place and call them when I need them, but I have no idea what that would look like....
That, in a nutshell, is the essence of the "Model" part of MVC, and at a more general level what Johanafm was referring to. Without even getting into classes/objects, you can functionalize common database actions. As a fairly simple, general example, you could create a function for generic select queries:
function select($tableName, $searchColumn, $searchValue)
{
$sql = sprintf(
"SELECT * FROM `%s` WHERE `%s` = %s",
$tableName,
$searchColumn,
(isNumeric($searchValue)) ? $searchValue : "'" . mysql_real_escape_string($searchValue) . "'"
);
$result = mysql_query($result);
if($result)
{
$data = array();
while($row = mysql_fetch_assoc($result))
{
$data[] = $row;
return $row;
}
}
error_log(mysql_error()."\n".$sql);
return false;
}
Now suppose that that function is in an include file, we'll call it "db.php", which also include a function called dbConnect() to establish your database connection. Then a page could use it something like:
<?php
session_start();
require_once "db.php";
if(!dbConnect())
{
die(Uh-oh!); // or whatever you want to do on a critical failure like that.
}
$userData = select('users', 'id', $_SESSION['user_id']);
if(!empty($userData)
{
echo "Hello, " . $userData[0]['first_name'] . ".";
}
else
{
// redirect to login page?
}
This only scratches the surface, but should give you a basic idea of a way to approach duplicating the same basic code in many places. The above code might itself be folded into some sort of isLoggedIn() function or a pageHeader() function, which would be included and called itself in the main page rather than calling the database functions directly. (Then you might be approaching the "controller" level of the MVC paradigm.)