douejuan9162 2013-11-14 20:22
浏览 30
已采纳

有没有办法在Functions.php文件中将PHP语句存储在PHP中?

Let's say I have a piece of code that is getting all records from a particular table. Such as:

mysql_select_db($database_localhost, $localhost);
$query_getTechs = "SELECT * FROM zip_tech ORDER BY tech_name ASC";
$getTechs = mysql_query($query_getTechs, $localhost) or die(mysql_error());
$row_getTechs = mysql_fetch_assoc($getTechs);
$totalRows_getTechs = mysql_num_rows($getTechs);

Is there a way to make this a function where the table name and sort by column are part of the function's arguments? So I could put something such as:

get_records('zip_tech','tech_name');

I end up with a lot of these on some things I'm trying to build as I learn PHP. It seems like having to use blocks of code like that repeatedly makes things more convuluted and less clean looking.

  • 写回答

1条回答 默认 最新

  • douguanyun2169 2013-11-14 20:29
    关注

    What you're looking for are, well, functions.

    http://www.php.net/manual/en/functions.user-defined.php A function for get_records would look something like this:

    function get_records($from, $order){
        $query = 'SELECT * FROM '.$from.' ORDER BY '.$order.' ASC';
        //whatever else you wanted
        return $query;
        }
    

    And you'd call it like this:

    $query = get_records('zip_tech','tech_name');
    

    You could also create a function without the return value, that preforms what you need. And call it by just invoking the function name and parameters.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部