Attarc
Attarc

Reputation: 3

In PHP and MySQL, my code only prints one row of the table's column

I'm a begginer with php, and I have some troubles with it. My question is about PHP and MySQL. The purpose of the code is that I have a parameter called $sql in which I will write the SQL query. The problem is that my code only prints one row of the consult. I mean, if I have a table with 4 columns (the attributes) and in that table I have 4 rows, the code only prints one row of each column.

The method consult code:

public function makeConsult($sql){
    $result = mysqli_query($this->conn, $sql);
    $nrows= mysqli_num_rows($result);
    if ($nrows> 0) {
        for($i = 0;$i<count($nrows);$i++) {
            $row= mysqli_fetch_array($result,MYSQLI_NUM);
            for ($j=0; $j < count($row) ; $j++) { 
                array_push($this->results, $row[$j]);
            }
        }
    } else {
        echo "No matches found";
    }
}

The following method is where I print all the consults:

public function printResult(){
    foreach ($this->results as $key => $value) {
       echo $key . ": " . $value . "<br>";
    }
    $this->results = array();
}

The variable $conn is the variable where I have my sql connection.

My execution code:

$db = new dbConnection("localhost","root","","sportsweb");
    $db->connect();
    echo "Database name: " . $db->getDBname();
    $consult = $db->makeConsult("SELECT * FROM articles A");
    $db->printResult();
    $db->closeConnection();

The columns (attributes) of the table "articles" are the following ones: Id,Name,Units,BranchOffice.

Thank you! :)

Upvotes: 0

Views: 395

Answers (1)

Machavity
Machavity

Reputation: 31624

You have two mistakes here

$nrows= mysqli_num_rows($result);
if ($nrows> 0) {
    for($i = 0;$i<count($nrows);$i++) {
        $row= mysqli_fetch_array($result,MYSQLI_NUM);
        for ($j=0; $j < count($row) ; $j++) { 
            array_push($this->results, $row[$j]);
        }
    }
}

So $nrows will be a count of how many rows you got back. So count($nrows) is useless because it's not an array

Second, I don't know where you got the idea to iterate rows like that, but you're doing it wrong. Use a while loop instead. I also removed the inner for loop and switched to a simpler foreach

$nrows= mysqli_num_rows($result);
if ($nrows> 0) {
   while($row = mysqli_fetch_array($result,MYSQLI_NUM)) {
        foreach($row as $val) $this->results[] = $val;
    }
}

Upvotes: 2

Related Questions