tags:

views:

112

answers:

2
+1  Q: 

Php syntax error

Hello! 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";  
    if ($rs = $conn->query($sql)) {   
        if ($row = $rs->fetch_assoc()) {    
            echo stripslashes($row['content']);   
        }
        $rs->close();  
    } 
} 
?>
+4  A: 

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()
Felix Kling
deleted mine, upvoted yours as it is more concise
Gordon
Ok thanks, for that now works. Im a little confused here as now it looks like this$conn = (get connection code)function getStuff($id, $conn){ (get id code)}getStuff(idRef, $conn);now how come the $conn passed in by the getStuff call is accessable there but if its not passed into the function the function cant access it. Am i going wrong by thinking all this code resides in a class, and therfore $conn would be a class variable which would be accessable by class methods? Im new to php, usually code java!
Dori
ok thanks for the edit. makes sense now. If this was contained in a class the function would have access to class variables though right?
Dori
@Dori: You are right, I updated my answer to provide a small example.
Felix Kling
+1  A: 

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

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

Otherwise the function can't see it.

cletus
This answer is good as it explains why it doesn't work, however Felix example is a slightly better example as far as a practical implementation goes as it's best to really try and avoid referencing global variables in functions where possible, particularly in PHP. In this scenario you might want to drop having a function all together. If it needs to be reusable you might want to check out something like http://www.php-editors.com/articles/simple_php_classes.php as a simple guide to creating nice, reusable OO classes in PHP.
Iain Collins
@Iain: well... I have a thing about overcomplicating PHP and trying to make it something it's not. I actually think a global DB connection is fine (and simple). I see people needlessly creating convoluted class hierarchies on top of this kind of thing all the time and it doesn't necessarily add any value.
cletus
I understand your point about simplification - there are far too many over complicated AND poorly written libraries for PHP, but I think the "trying to make PHP something it's not" comment comes across as a bit snide. I take the view that using globals inside methods also over complicates things, in the same way that not using OO principles does (trivial use cases aside). If you do use globals anywhere then I strongly advocate using the superglobal $GLOBALS (e.g. $GLOBALS['conn']) as it's immediately clear everywhere they are being used and they don't need to be explicitly declared.
Iain Collins