How to put mysql inside a php function?

后端 未结 6 1007
梦谈多话
梦谈多话 2021-01-14 15:37

I have problem about putting mysql into a function showMsg(). The mysql is working fine if it is not wrapped by function showMsg(), but when I wrap it with function showMsg(

6条回答
  •  隐瞒了意图╮
    2021-01-14 15:58

    As everyone mentioned, the issue has to do with variable scoping. Instead of add global $connection; you could consider a more OOP approach and consider:

    A: passing the $connection variable into the function.

    B: placing related functions in a class and pass the DB connection into the Class constructor. for example:

    class YourClass  {
    
       private $connection;
    
       public function __construct($connection) {
           $this->connection = $connection;
       }
    
       public function showMsg(){   
            $query2 = "SELECT id, message, username, datetime FROM messageslive ORDER BY id DESC LIMIT 20";
            $result2 = mysql_query($query2,$this->connection) or die (mysql_error());
            confirm_query($result2);
            $num = mysql_num_rows($result2); 
            while($msginfo = mysql_fetch_array($result2)){
                echo $msginfo['message'];
                echo $msginfo['username'];
            }
       }
    
    }
    

    I don't have enough rep to comment. But I also like OZ_'s answer :)

提交回复
热议问题