How to put mysql inside php function?

I have a problem placing mysql in showMsg () function. Mysql works fine if it is not completed by the showMsg () function, but when I wrap it with the showMsg () function, it gives the error message "Warning: mysql_query (): the provided argument is not valid". How to put mysql inside php function? Below are my codes:

<?php    
function showMsg(){   
        $query2 = "SELECT id, message, username, datetime FROM messageslive ORDER BY id DESC LIMIT 20";
        $result2 = mysql_query($query2,$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'];
        }
}

<div>
   <?php showMsg(); ?>
</div>
?>
+3
source share
6 answers

You will probably need:

global $connection;

(inside the function, that is.)

Cm. Variable Scope

+7
source
  • Never use global.
    Pass $connectionin your function as an argument.

  • .
    MVC: .

  • , . - - .

+7

, . add global $connection; OOP :

A: $connection .

B: DB- . :

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'];
        }
   }

}

. OZ_ :)

+3

$connection . ( ):

global $connection;

, , :

  • () $connection
  • $connection ( )
  • redeclare $connection variable ( : ),
+2

. :

global $connection;
+1

, - . global $connection .

-1

All Articles