1

So i have this class for loading data from my MySQL database :

class Db {

    protected static $connection;

    public function connect() {    
        if(!isset(static::$connection)) {
            $config = parse_ini_file('config.ini'); 
            static::$connection = new mysqli('localhost',$config['username'],$config['password'],$config['dbname']);
        }
        if(static::$connection === false) {
            return false;
        }
        return static::$connection;
    }


    public function query($query) {
        return $this->connect()->query($query);
    }

    public function select($query) {
        $rows = array();
        $result = $this->query($query);
        if($result === false) {
            return false;
        }
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
        return $rows;
    }

    public function error() {
        return $this->connect()->error;
    }

    public function quote($value) {
        return "'" . $this->connect()->real_escape_string($value) . "'";
    }
}

I use that class like this :

$db = new Db();
$rows = $db -> select("SELECT name, shortlink FROM `test` WHERE id=3");

It gives me an array with the data.

The problem is that i want to pull out specific data, for example the shortlink field.

How do i do that? I have tried echo $rows['shortlink'], but that gives me the following error :

Undefined index: shortlink

So how do I print specific data?

1
  • I would suggest using more convenient approach to fetch values of a certain field with PDO (PDO::FETCH_COLUMN) Commented Feb 14, 2016 at 18:22

1 Answer 1

1

Your returned $rows columns is an array of associative arrays, to pull out shortlink data returned from the query you have to do something like this:

foreach($rows as $row) {
   echo $row['shortlink'];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.