Note that there are some explanatory texts on larger screens.

plurals
  1. POFetching rows using PHP OO Class
    text
    copied!<p>I have made a class function which will get rows from a table in my database along with an optional argument. This works when getting a single row however I cant get this to work when multiple rows are returned.</p> <p>Here is what is in the Users class</p> <pre><code>public function getUsers($filter="") { $Database = new Database(); if($filter == 'male') $extra = "WHERE gender = 'm'"; $sql = "SELECT * FROM users $extra"; if ($Database-&gt;query($sql)) return $Database-&gt;result-&gt;fetch_assoc(); else return false; } </code></pre> <p>Database Class</p> <pre><code>class Database { private $db = array(); private $connection; private $result; public function __construct() { $this-&gt;connect(); } public function connect() { $this-&gt;connection = mysqli_connect('mysql.com', 'username', 'pass'); mysqli_select_db($this-&gt;connection, 'database'); } public function query($sql) { $this-&gt;result = mysqli_query($this-&gt;connection, $sql); return $this-&gt;result; } </code></pre> <p>This is the code used to try and display the rows</p> <pre><code>if ($student = $User-&gt;getUsers($filter)) { echo "&lt;table&gt;\n"; echo "&lt;tr&gt;&lt;td&gt;Col 1&lt;/td&gt;&lt;td&gt;Col 2&lt;/td&gt;&lt;td&gt;Col 3&lt;/td&gt;&lt;td&gt;Col 4&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;"; foreach($student as $row) { echo "&lt;tr&gt;"; echo "&lt;td&gt;$row[col1]&lt;/td&gt;"; echo "&lt;td&gt;$row[col2]&lt;/td&gt;"; echo "&lt;td&gt;$row[col3]&lt;/td&gt;"; echo "&lt;td&gt;$row[col4]&lt;/td&gt;"; echo "&lt;td&gt;$row[col5]&lt;/td&gt;"; echo "&lt;td&gt;$row[col6]&lt;/td&gt;"; echo "&lt;/tr&gt;\n"; } echo "&lt;/table&gt;"; } </code></pre> <p>(I'm learning OO PHP, bear with me) </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload