Okay, so I have this code, works great for saving a video object that's passed through it. I put this together because someone said I shouldn't be doing queries directly within the Video class functions, I should have an external class devoted to interacting with the database for it.
class VideoHandler {
private $myObject;
function __construct($object) {
$bind = array();
$bind[':src'] = $object->src;
$bind[':title'] = $object->title;
$bind[':desc'] = $object->desc;
$bind[':cat_id'] = $object->cat_id;
$bind[':game_id'] = $object->game_id;
$this->myObject = $object;
}
function save($conn) {
$sql = "INSERT INTO videos (`src`, `title`, `desc`, `cat_id`, `game_id`) VALUES (:src, :title, :desc, cat_id, :game_id)";
$query = $conn->prepare($sql);
$query->execute($this->myObject);
return "Video Saved!";
}
}
So this is all fine and dandy for saving, but I want to be able to get related videos, get top videos, update the views on a video, etc.
So let's say hypothetically I want to add views to the video with something like this:
function updateViews($conn) {
$sql = "UPDATE videos SET views=(:views+1) WHERE id=:id";
$query = $conn->prepare($sql);
$query->execute($this->myObject);
}
It won't work because there's too many binded variables (I know I don't have views or id bounded, but that's irrelevant anyway).
Is there a better way to construct the VideoHandler to be able to do these multiple functions without repeating a lot of code? The two solutions I thought of seem wrong to me. I was thinking I could just have multiple bind arrays in the constructor for each function, and multiple attributes to store the arrays.
So $bind_save, $bind_views, $bind_related, etc. Where I only put in the parts of the object I'd use for the different queries in each array.
Either that or pass the object into the function itself and just bind everything inside there, but that doesn't seem right either.
It seems strange that I can't just add $bind[':id'] and $bind[':views'] into the array in the constructor and just use the code I posted above. Maybe I'm missing something, but why does every piece of the array have to be used in the PDO execute? How come I can't just have the full array and only use the ones that are being used in the $sql query?
Anyway, is there a better way to do it than the ways I mentioned? I feel like there must be.
Thanks