Using string value in class

Hi, im using a gallery script and don’t seem able to pass use the string in the class:

<?php
 
class DB{
    //database configuration
    private $dbHost     = " ";
    private $dbUsername = " ";
    private $dbPassword = " ";
    private $dbName     = " ";
    private $imgTbl     = '';
	
   
    function getRows(){
        $query = $this->db->query("SELECT * FROM ".$this->imgTbl." WHERE cat2 = $did ORDER BY img_order ASC");
        if($query->num_rows > 0){
            while($row = $query->fetch_assoc()){
                $result[] = $row;
            }
        }else{
            $result = FALSE;
        }
        return $result;
    }

Prior to the class i can echo $did, however after the class, how do i retrieve/use the string in the query? If i manually ad the $did ‘number’ in the query it functions correctly.

Thanks in advance

That’s because the variable is not global outside of its scope. If you aren’t extending the db file, you can do

$class = new DB();
print_r($class->getRows());

The above snippet is untested, but I assume would work.


Edit: now that I think about it, it’ll most likely fail unless you extends your DB file.

Read these three topics throughly

  1. http://php.net/manual/en/language.variables.scope.php
  2. http://php.net/manual/en/functions.arguments.php
  3. http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

hum, ok…ive got it working, by setting

$did = $_GET['id'];

prior to the include, then using

global $did ;
$query = $this->db->query("SELECT * FROM ".$this->imgTbl." WHERE cat2 = $did ORDER BY img_order ASC");

That’s the worst thing you could have done. It’s both insecure and unmaintainable.
My condolences to this script’s future owner.

Pass it as parameter to the function instead of using globals. You should also use prepared statements to prevent SQL injection as @colshrapnel mentioned.

$did = $_GET['id'];
$db = new DB();
$rows = $db->getRows($did)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.