du8794 2016-08-20 17:30
浏览 46

PHP PDO查询对象和函数内部,关于绑定

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

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
    • ¥15 seatunnel 怎么配置Elasticsearch
    • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
    • ¥15 (标签-MATLAB|关键词-多址)
    • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
    • ¥500 52810做蓝牙接受端
    • ¥15 基于PLC的三轴机械手程序
    • ¥15 多址通信方式的抗噪声性能和系统容量对比
    • ¥15 winform的chart曲线生成时有凸起
    • ¥15 msix packaging tool打包问题