【问题标题】:PHP Class uses Static DB Table/Column Names. How to make Dynamic? (BEST PRACTICES)PHP 类使用静态数据库表/列名称。如何制作动态? (最佳实践)
【发布时间】:2012-11-13 20:24:09
【问题描述】:

我找到了一个基于 PHP 的食谱和膳食计划脚本,我想对其进行编辑。

MealPlan 类允许所有用户通过从数据库中找到的所有食谱列表中进行选择来创建自己的每日菜单/膳食计划。

我想根据用户的级别切换insert语句中使用的表/列名。

原来的插入方法是:

// Insert Meal Plan
function insert($date, $meal, $recipe, $servings, $owner) {
        global $DB_LINK, $db_table_mealplans, $LangUI;

        $date = $DB_LINK->addq($date, get_magic_quotes_gpc());
        $meal = $DB_LINK->addq($meal, get_magic_quotes_gpc());
        $recipe = $DB_LINK->addq($recipe, get_magic_quotes_gpc());
        $servings = $DB_LINK->addq($servings, get_magic_quotes_gpc());
        $owner = $DB_LINK->addq($owner, get_magic_quotes_gpc());

        $sql = "INSERT INTO $db_table_mealplans (
          mplan_date,
          mplan_meal,
          mplan_recipe,
          mplan_servings,
          mplan_owner)
          VALUES (
          '$date',
          $meal,
          $recipe,
          $servings,
          '$owner')";
        $rc = $DB_LINK->Execute($sql);
        DBUtils::checkResult($rc, NULL, $LangUI->_('Recipe already added on:'.$date), $sql);
}

我的想法是改变:

mplan_date,
mplan_meal,
mplan_recipe,
mplan_servings,
mplan_owner

到:

$mplan_date,
$mplan_meal,
$mplan_recipe,
$mplan_servings,
$mplan_owner

并使用 switch 语句更改表/列名称。但有人告诉我,这种事情在 OOP 中是不受欢迎的。解决这个问题的最佳方法是什么?

(注意:如果需要,我可以发布整个课程,但我认为这已经足够了)

【问题讨论】:

  • db_table_mealplans 中还有哪些其他列可以切换到?这听起来不像你有编程问题,听起来更像是应用程序设计/数据设计问题。如果你必须尝试完成这样的事情,你可能会做错事。

标签: php class methodology object-oriented-database


【解决方案1】:

我没有任何代码给你,但我最近做了类似的事情。基本上,我通过根据用户输入的内容连接字符串来动态创建 SQL 字符串。请耐心等待我尝试即时输入内容。

$columnsArray = array();
$sqlCmd = "INSERT INTO";

If (someCondition) {
    array_push($columnsArray, "mplan_date");
}//Could try turning this into a loop and just push all 
 //applicable columns into the array

$counter = 0;

Foreach ($columnsArray as $columnName) {
    $sqlCmd .= " $columnName";
    $counter++
    If ($counter < count($columnsArray)){
        $sqlCmd .= ",";
    }//This will put a comma after each column with the 
     //exception of the last one.
}

所以我只用用户定义的选择语句来检索数据就做了这样的事情。基本上继续执行逻辑,直到您构建了一个自定义字符串,该字符串将成为用户定义的 SQL 语句,然后执行它。这包括执行类似于上述脚本的操作以将值连接到字符串中。

希望这能给你一些想法。

【讨论】:

  • 还有很多测试来自 html 中的 $_POST 表单,并检查是否设置了预加载其他变量以用于构建 SQL 语句。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-24
  • 1970-01-01
  • 2013-01-24
  • 2020-02-28
  • 2011-09-04
相关资源
最近更新 更多