将 SQL 查询放入 PHP 函数中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6765327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:11:06  来源:igfitidea点击:

Putting a SQL query in a PHP function

phpmysql

提问by saltcod

I've got several queries I want to run on a single page. I obviously don't want to put the actual queries in my template file, so I thinkwhat I want to do is construct a function and call it wherever I want the query results to show up. Right?

我有几个要在单个页面上运行的查询。我显然不想把实际的查询放在我的模板文件中,所以我我想做的是构造一个函数并在我希望查询结果显示的任何地方调用它。对?

So, for example, I'll have <?php sidebar_query()?>in the sidebar, <?php footer_query()?>in the footer, etc.

因此,例如,我将<?php sidebar_query()?>在侧边栏、<?php footer_query()?>页脚等中添加。

So, I just make a file called functions.php, do PHP include, and put something like this in there?

所以,我只是创建一个名为 的文件functions.php,是否包含 PHP,并在其中放入类似的内容?

<?php
    function sidebar_query(){
        $query = ("SELECT sidebarposts FROM table;");
    return $query;
}
?>

or do you use echoand not return anything?

或者你使用echo并且不返回任何东西?

<?php
    function sidebar_query(){
        $query = ("SELECT sidebarposts FROM table;");
        echo $query;
}
?>

Along the exact same line, I'd like to count the results that get returned, and display a 'There were X posts returned!' message below. Seems like it would make sense to put this in a function too. How would I make a 'generic' function that I could reuse for each query?

沿着完全相同的路线,我想计算返回的结果,并显示“返回了 X 个帖子!” 下面留言。似乎把它放在一个函数中也是有意义的。我将如何制作一个可以为每个查询重用的“通用”函数?

<?php
    function number_of_results(){
        $num_rows = mysql_num_rows();
        echo $num_rows;
}
?>

I'd be extremely grateful if someone could give me the theoretical gist of what I should be trying to achieve here.

如果有人能给我我应该在这里努力实现的理论要点,我将不胜感激。

Thanks for helping a beginner.

感谢您帮助初学者。

Terry

特里

回答by Fredrik

I think I get what you mean.

我想我明白你的意思。

Return the value instead like this

像这样返回值



    function sidebar_query(){
        $rValue = "";
        $query = ("SELECT sidebarposts FROM table;");
        $result = mysql_query($query);
        if ($row = mysql_fetch_array($result)){
            $rValue = $row['sidebarposts'];
        }
    return $rValue;
    }

Now you can echo sidebar_query(); or whatever you want to do with it.

现在你可以 echo sidebar_query(); 或者你想用它做什么。

回答by joakimdahlstrom

By doing ("SELECT sidebarposts FROM table;")you're not actually doing anything, you just have a string stored as a variable.

通过这样("SELECT sidebarposts FROM table;")做,您实际上并没有做任何事情,您只是将一个字符串存储为变量。

A simple example is

一个简单的例子是

function sidebar_query()
{
    $query = mysql_query("SELECT title,post FROM table;"); //query the db
    $resArr = array(); //create the result array

    while($row = mysql_fetch_assoc($query)) { //loop the rows returned from db
        $resArr[] = $row; //add row to array
    }

    return $resArr;   
}

Then to use it you can do

然后使用它你可以做

$sideBarPosts = sidebar_query(); //get the result array

foreach($sideBarPosts as $post) { //loop the array
    echo '<h1>'. $post['title']. '</h1>';
    echo '<p>'. $post['post']. '</p>';
}


EDIT. I see you want to let the function print it directly, you can do that instead of returning the array, if you like.

编辑。我看到你想让函数直接打印它,如果你愿意,你可以这样做而不是返回数组。

回答by Muhammad Shahzaib

   function sidebar_query(){
    $query = mysql_query("SELECT * FROM table;");
    $result = $conn->query($query);
    $resArr = array(); //create the result array

    while($row = $result->fetch_assoc()) { //loop the rows returned from db
      $resArr[] = $row; //add row to array
    }
    return $resArr;   
    }

and that :

然后 :

    $sideBarPosts = sidebar_query(); //get the result array

    foreach($sideBarPosts as $post) { //loop the array
      echo '<h1>'. $post['title']. '</h1>';
      echo '<p>'. $post['post']. '</p>';
    }

回答by Montree Amatasuwan

// Set Connection with database

// 设置与数据库的连接

$conn = mysql_pconnect($servername,$username,$password) or die("Can not Connect MySql Server!");

// Select database you want to use

// 选择要使用的数据库

mysql_select_db($databasename,$conn) or die("Can not select Data Base!");

// When you want to query SQL inside php function, you need to pass connection($conn) to the function as below.

// 当你想在 php 函数中查询 SQL 时,你需要将 connection($conn) 传递给函数,如下所示。

function sidebar_query($condb)
   {
     $strSql = "SELECT sidebarposts FROM table";
     $result = mysql_query($strSql,$condb);
     return $result;
   }

// Call function

// 调用函数

 sidebar_query($conn);

This is work for me as i use with my webpage.

这对我有用,因为我在我的网页上使用。

回答by dragon

Although in this case i dont think there is really enough extra logic to warrant wrapping it in a function. I would probably just do this directly in my template.

尽管在这种情况下,我认为没有足够的额外逻辑来保证将其包装在函数中。我可能会直接在我的模板中执行此操作。

A good example of where something like this is useful is if you want to do "time in words" functionality like "Yesterday" or "10 minutes ago" then you would pass in the time calculate which string to use, format it

像这样有用的一个很好的例子是,如果您想执行“用文字表示的时间”功能,例如“昨天”或“10 分钟前”,那么您将传入时间,计算要使用的字符串,对其进行格式化

回答by matasoy

You need to pass database connection name to function like this,

您需要将数据库连接名称传递给这样的功能,

You already have a connection name, mine is $connect_name

你已经有一个连接名称,我的是 $connect_name

$connect_name= mysql_connect( 'host', 'user', 'password');

function getname($user,$db){
    $data= mysql_query("SELECT $user...", $db);
    //your codes
    //return bla bla
}

echo getname("matasoy",$connect_name);

This work for me.

这对我有用。

I also use this for medoo.minsql system. You can use medoo with functions like this;

我也将它用于medoo.minsql 系统。您可以将 medoo 与这样的功能一起使用;

function randevu($tarih,$saat,$db){

    $saat_varmi = $db->count("randevu",array("AND"=>array("tarih"=>$tarih,"saat"=>$saat)));

    if($saat_varmi>0)
        return 3;
    else
        return 2;               
}

have a nice day, Murat ATASOY

祝你有美好的一天,Murat ATASOY

回答by Naftali aka Neal

Read the php doc on how to run mysql query.

阅读有关如何运行 mysql 查询的 php 文档。

Yayyou have the query, now you need to do something with it:

Yay你有查询,现在你需要对它做一些事情:

mysql_query($query);for example might work for you :-)

mysql_query($query);例如可能对你有用:-)

回答by prodigitalson

You want to run the query and return the result in whatever format you want to use in your template.. so for the raw number you want to return an integer, for the sidebar posts return an array of posts OR the mysql result.

你想运行查询并以你想在模板中使用的任何格式返回结果..所以对于你想要返回一个整数的原始数字,对于侧边栏帖子返回一个帖子数组或 mysql 结果。

You should make the "'There were X posts returned!' " thing a completely different function which you can pass in an integer an an optional string. This way you can reuse it for a ton of stuff. for example:

你应该让“'有X个帖子返回!' " 一个完全不同的函数,你可以传入一个整数和一个可选的字符串。这样你就可以将它重用于大量的东西。例如:

function format_nb_records($nb_records, $format = 'There were %s posts returned!'){
   return sprintf($format, $nb_records);
}

Although in this case i dont think there is really enough extra logic to warrant wrapping it in a function. I would probably just do this directly in my template.

尽管在这种情况下,我认为没有足够的额外逻辑来保证将其包装在函数中。我可能会直接在我的模板中执行此操作。

A good example of where something like this is useful is if you want to do "time in words" functionality like "Yesterday" or "10 minutes ago" then you would pass in the time calculate which string to use, format it and return it.

像这样有用的一个很好的例子是,如果您想执行“用文字表示的时间”功能,例如“昨天”或“10 分钟前”,那么您将传入时间计算要使用的字符串,对其进行格式化并返回它.