开发者

"Undefined Variable" notice

Im new to php so im sure this is an easy one. Im getting this error

Notice: Undefined variable: conn in C:\Dev\Webserver\Apache2.2\htdocs\EclipsePHP\thecock\php\db.php on line 23

for this code

<?php
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";

$conn = new mysqli($host, $username, $password, $database);

if (! $conn) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit(); 
}else{  
    echo("all ok!"); 
}

function getContent($id) {  
    $sql = "SELECT content FROM blocktext WHERE id=$id";  
  开发者_JAVA技巧  if ($rs = $conn->query($sql)) {    # line 23
        if ($row = $rs->fetch_assoc()) {    
            echo stripslashes($row['content']);   
        }
        $rs->close();  
    } 
} 
?>

How do I fix the notice?


Change your function to:

function getContent($id, $conn) {
     $sql = "SELECT content FROM blocktext WHERE id=$id";
     if ($rs = $conn->query($sql)) {
        if ($row = $rs->fetch_assoc()) {
           echo stripslashes($row['content']);
         }
        $rs->close();
     }
}

You don't declare the "original" $conn in the scope of the function. Inside the function you only have access to variables declared inside the function or provided via parameters.

Another way would be to declare the variable as global in your function:

function getContent($id) {
     global $conn;
     $sql = "SELECT content FROM blocktext WHERE id=$id";
     if ($rs = $conn->query($sql)) {
         if ($row = $rs->fetch_assoc()) {
             echo stripslashes($row['content']);
         }
     $rs->close();
     }
}

But you should only do this, if there is no other way. Globals make it hard to debug and maintain the code.

See also Variable scope and why global variables are bad.

Edit:

Yes e.g. you can have a DB class:

class DB {
   private static $conn = null;

   public static function getConnection() {
      if (is_null(DB::$conn)) {
         $host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
         DB::$conn = new mysqli($host, $username, $password, $database);
      }
      return DB::$conn;
   }
}

Of course this is not the best implementation ;) But it should give you the right idea. Then you can get the the connection:

DB::getConnection()


conn is a global variable. To access it within a function:

function getContent($id) { 
  global $conn;
  ...
}

Otherwise the function can't see it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜