About Mysqli functions

Asked

Viewed 402 times

3

I have a question about some function of Mysqli

In the conventional way we would do so:

public function Numrows($sql) {
      return mysqli_num_rows($sql);
}

And how I’m using extends mysqli I’m doing this:

public function dbNumRows($Query) {

    $sql = parent::prepare($Query);

    return $sql->num_rows();
}

What is the most correct way to return line numbers using PHP Oriented with class extends mysqli?

Full class of the connection

<?php

class Connect extends mysqli {

    public $db_connection, $db_hostname, $db_username, $db_password, $db_database;

    public function __construct() {
        $this->db_hostname = DB_HOSTNAME;
        $this->db_username = DB_USERNAME;
        $this->db_password = DB_PASSWORD;
        $this->db_database = DB_DATABASE;

        $this->connectMe();
    }

    private function connectMe() {
        $this->db_connection = @$this->connect($this->db_hostname, $this->db_username, $this->db_password, $this->db_database);

        if ($this->connect_error) {
            die("Falha na tentativa de se conectar com o servidor: " . $this->connect_error);
        }
    }

    public function dbExecute($Query) {
        $Result = $this->query($Query);

        if ($this->error) {
            die("Erro no comando: $Query");
        }

        return $Result;
    }

    public function dbNumRows($Query) {
       return $this->prepare($Query)->num_rows();
    }

}

Att.

2 answers

2


If you’re inheriting from the class mysqli all available methods will be in your new class. No need to create new methods for this:

<?php

class MeuBanco extends mysqli{

    // ...

}

$db = new MeuBanco();
$db->prepare('SELECT * FROM test')->num_rows();

If you want to use the methods of mysqli within your class do not need to use parent::, can use the $this as if it were a class method.

public function dbNumRows($query) 
{
    return $this->prepare($query)->num_rows();
}

Another way is to edit your function to receive the mysqli_result:

public function dbNumRows(mysqli_result $query) 
{
    return $query->num_rows;
}

Note that num_rows is a property of mysqli_result, so this should work too:

<?php

$query = $Connect->dbExecute("SELECT * FROM oop_usuarios"); 
$num = $query->num_rows;
  • I’ve tried to use as you recommended but got back two errors see: Warning: mysqli::prepare() expects parameter 1 to be string, object given in C:\wamp\www\oop\modules\class\Connect.class.php on line 35 the other mistake: Fatal error: Call to a member function num_rows() on a non-object in C:\wamp\www\oop\modules\class\Connect.class.php on line 35 this is my method public function dbNumRows($Query) {&#xA; return $this->prepare($Query)->num_rows();&#xA; }

  • @Guilhermealves you are passing an incorrect argument. The method prepare expects a string, and you’re passing something else.

  • I am passing a variable that is the parameter I am passing here see: $query = $Connect->dbExecute("SELECT * FROM oop_usuarios"); $num= $Connect->dbNumRows($query ); I’m at my job now when I get home I see what I can do, if you have any tips...

  • @Guilhermealves this way is wrong. Post your complete connection class in the question.

  • was added in the topic.

  • @Guilhermealves Tente $db->dbNumRows('SELECT * FROM oop_usuarios');. Pass only the query SELECT * FROM oop_usuarios

  • Yes this way right, but I wanted to take the parameter passed!

Show 3 more comments

0

It seems that you are passing the query already made to the class method. This is incorrect. You are mixing procedural call with object-oriented.

Once the query is done you should only use it to extract the data, and not pass to another constructor. Even in an inherited class.

The function dbNumRows is not necessary and may be withdrawn,

$cn = Connect();
$query = $cn->dbExecute('SELECT * from table'); // A query está pronta
$nr = $query->num_rows; // Lendo número de linhas da query

Ref.: http://php.net/manual/en/mysqli-result.num-rows.php

Note that neither the dbExecute is necessary, but I have considered that it can do something different from the standard execution of query.

If you are going to use prepare, there is a little more code, but it keeps the same process of not creating the same object, create one and use the inputs and outputs of data from it.

Edition 2015-05-24: Example of a descending class of the class mysqli:

Install XAMPP (tested with xampp-Win32-5.6.8-0-VC11-installer.exe); Create a PHP file and copy the following content into it:

<?php
/*
 * Estende a classe mysqli com uma função para fazer uma query a uma tabela
 * específica.
 */
class MinhaConexao extends mysqli {
    function MinhaQuery($filtro) {
        $sql = 'SELECT * FROM cds';
        if ($filtro != '') {
            $sql = $sql . ' WHERE ' . $filtro;
        }
        return parent::query($sql);
    }
}

$cn = new MinhaConexao('localhost', 'root', '', 'cdcol');

if (isset($_POST['from'])) {
    $from = intval($_POST['from']);
} else {
    $from = 1990;
}

if (isset($_POST['to'])) {
    $to = intval($_POST['to']);
} else {
    $to = 2005;
}
?><html>
    <head>
        <title>Teste com classe herdada do MySQLi</title>
    </head>
    <body>
        <form method="post" action="<?php print($_SERVER['SCRIPT_NAME']); ?>" enctype="multipart/form-data">
            Ano de <input type="text" name="from" value="<?php echo $from; ?>"/> a <input type="text" name="to" value="<?php echo $to; ?>"/>
            <input type="submit" />
        </form>
        <?php
        $query = $cn->MinhaQuery('(jahr >= ' . $from . ') AND (jahr <= ' . $to . ')');
        ?>
        Quantidade: <?php print_r($query->num_rows); ?>
        <?php
        while ($r = $query->fetch_assoc()) {
            print('<p>');
            print_r($r);
            print('</p>');
        }
        $query->close();
        ?>
    </body>
</html><?php
$cn->close();
?>

Open the XAMPP control panel, enable Apache and Mysql servers and access the file created with the browser.

  • Is I can’t return the number of lines even that cow coughs! You would have some tutorial similar to what I’m trying to do?

  • I don’t have a tutorial, but I created a complete example of a class and use it. I didn’t even worry about safety, the focus is just the class and its use, on the Oop model. Note that the query variable is not passed as parameter, it has its properties and functions, and is what should be used.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.