António Matos António Matos - 6 months ago 37
PHP Question

Cant call same function twice in same php page

Im trying to call my function "selectuniversal();" twice in the same page, but i only get results from the first call(or the secound if i disable 1st call).

My function is:
[ func.php ]

<?php
global $mycon;
$mycon = mysqli_connect('localhost','user','pass','db');
$mycon->set_charset('utf8');
class IDfun{

public function selectuniversal($tabela,$celula1,$celula2,$celulaordem,$ordem)
{
global $mycon;

$IDquery = 'SELECT '.$celula1.','.$celula2.' FROM '.$tabela.' ORDER BY '.$celulaordem.' '.$ordem;
$IDresultado= mysqli_query($mycon,$IDquery) or die(mysqli_error());

do{
$i=$row[$celula1];
if($i>=1){echo '<option value='.$row[$celula1].'>'.$row[$celula2].'</option>';}
} while ($row = mysqli_fetch_assoc($IDresultado));
$mycon->close();
}

}

?>


In my [index.php]

<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"></meta>
<?php
include("func.php");
$IDfun=new IDfun;
?>

<meta charset="utf-8">
<title>Documento sem título</title>
</head>

<body>
<select id="cpais" name="cpais">
<?php $IDfun->selectuniversal('pais','pid','pnome','pnome','desc');?>
</select>

<p>

<select id="cvendid" name="cvendid">
<?php $IDfun->selectuniversal('vend','vid','vnome','vnome','desc');?>
</select>
</body>
</html>


Thanks you for any help

Answer

You're closing the mysqli connection in your function call $mycon->close(), so the second time you call the function the mysqli_query is trying to use a connection that has been closed.

Either create the connection in your function, or call $mycon->close() outside of your function at the end of your php file.

Comments