Carlos Vázquez
Carlos Vázquez

Reputation: 13

PHP Function doesn't work the second time I call it

I have a problem, I created a function that returns the result of a query to a combobox, it works fine, but when I call it the second time it doesn't work.

conexion.php

<?php
 $db = new mysqli('localhost', 'root', 'pass', 'table');
 $db->set_charset("utf8");
 if($db->connect_errno > 0){
    die('Cannot connect [' . $db->connect_error . ']');
 }
?>

consulta.php

<?php
class consulta{

public function get_combo($tabla,$nombre,$valor,$vista){


    require_once 'conexion.php';

    $sql ='SELECT * FROM '.$tabla; 

    if(!$result = $db->query($sql)){
        die('Ocurrio un error ejecutando el query [' . $db->error . ']');
    }
   $combo.=" <option value='0' selected disabled   class='combo'>$nombre</option>";
   while ($row =$result->fetch_assoc()) {
   $comboestado .=" <option value='".$row[$valor]."'>".$row[$vista]."</option>";

}
    $db->close();
    return $combo;

 }
}

?>

index.php

<?php 

    include_once '../php/consulta.php';
    $consulta = new consulta();
    $comboState=$consulta->get_combo('state','State','id','name');
    $comboTown=$consulta->get_combo('town','Town','id','name');

?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
 <select name="" id="state" class="form-group form-control">

    <?php echo $comboState; ?>

 </select>

 <select name="" id="town" class="form-group form-control">

    <?php echo $comboTown; ?>

 </select>
</body>
</html>

The function works the first time, but when I add the second call it doesn't work, even if I use the same parameters.

Upvotes: 1

Views: 837

Answers (1)

rgoble
rgoble

Reputation: 329

On the first call to get_combo, the require_once causes conexion.php to be loaded, which creates the mysqli. However once the get_combo function exits the $db variables goes out of scope and will be cleaned up.

On the second call to get_combo, the conexion.php file is not loaded again, so $db doesn't exist.

Upvotes: 2

Related Questions