Connection class mysqli in php and SELECT

Asked

Viewed 787 times

0

The connection code with the database I built is working, but when I use a SELECT an error appears and I could not solve.

<?php
define('DB_NAME', 'projetoxyz');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');

class conexao extends mysqli {

    public $servidor;
    public $usuario;
    public $senha;
    public $banco;

    function __construct($servidor, $usuario, $senha, $banco) {
        $this->servidor = $servidor;
        $this->usuario = $usuario;
        $this->senha = $senha;
        $this->banco = $banco;
    }

    public function conectar()
    {
        try
        {
            parent::__construct($this->servidor, $this->usuario, $this->senha, $this->banco);
            if(mysqli_connect_errno() != 0)
            {
                throw new Exception('Erro ao conectar!');
            }
        }
        catch(Exception $e)
        {
            echo $e->getMessage();
        }
    }
}

$mysqli = new conexao(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

#################################################################

if( !function_exists('nomecidade') ) {

    function nomecidade($cidade=NULL) {

        if(!isset($mysqli)) {
          $mysqli = new conexao(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
        }

        $mysqli->conectar();

        $cidade = trim($cidade);

        $cidade = $mysqli->real_escape_string($cidade);

        /* Em WHERE, o campo Código é INTEGER, o SELECT pega o código da Cidade e retorna o nome da cidade relacionada ao código*/

        $sqlCidade = "SELECT 
                            `Nome` 
                        FROM 
                            `municipio` 
                        WHERE 
                            `Codigo` = ? 
                        LIMIT 
                            1
                        ;";

        $stmt = $mysqli->prepare($sqlCidade);

        $stmt->bind_param("i", $cidade);

        $stmt->execute();

        $result = $stmt->get_result();

        if($result->num_rows === 0) exit('Cidade indefinida');

        $row = $result->fetch_assoc();

        $cidade = stripslashes( $row['Nome'] );

        $stmt->close();

        return $cidade;

    }
}

echo nomecidade('1100056');
?>

The error you see on the screen is as follows:

Fatal error: Uncaught Error: Call to a Member Function bind_param() on Boolean in F: xampp htdocs projetoxyz Conn.php:67

Stack trace: #0 F: xampp htdocs projetoxyz index.php(331): nomecity('1100056') #1 {main} thrown in F: xampp htdocs projetoxyz index.php on line 67

  • Friend, has this code been copied? You are using simple quotes in two ways, this can cause problems. Have you been able to perform another query before? Ideally, follow the W3 standards: https://www.w3schools.com/php/php_mysql_select.asp

  • The connection was copied.

  • I did as suggested, but how do I use the escape_string within my SELECT query ?

  • Your SELECT doesn’t even need quotes: $sql = "SELECT Name FROM municipio WHERE Code = ? LIMIT 1";

1 answer

1

I don’t think you created the statment, only then to use the prepare. Because when calling the function prepare will be returned a boolean (which results in the error you received, as a boolean value will not have the property bind_param). Do Something like:

//......
$stmt =  $mysqli->stmt_init();
$stmt->prepare($sqlCidade);

$stmt->bind_param("i", $cidade);

$stmt->execute();
//.......

Browser other questions tagged

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