每次我想在PHP中运行查询时,我应该初始化MySQL吗?

I have a little (and stupid) problem: I'm building a PHP application using mysqli and a MySQL server. When the application is loaded, a variable called $database is initialized using

$database = new mysqli($dbHost, $dbUser, $dbPassword, $dbName);

This, of course, works perfectly. If I create an statement to do a query:

$stmt = $database->prepare('SELECT a, b, c FROM table WHERE a = ?');

This still works. But, if I try to create another statement without closing the previous one, sometimes works, and sometimes now. The error I get when the creation of the statement fails is:

Fatal error: Call to a member function bind_param() on a non-object

And my question is: why? What should I do, open a connection (new mysql(...)) every time I want to create a new statement (and I have another open)?

Example

$stmt = $database->prepare('SELECT a, b, c FROM table WHERE a = ?');
$stmt->bind_param('i', $aValue);
$stmt->execute();
/* do some other operations, without closing $stmt */
$stmt2 = $database->prepare('INSERT INTO table2 (e, f) VALUES (? ,?)');
// Now, $stmt2 isn't initialized, so when the next line is run, the app fails
$stmt2->bind_param('ss', $someValue, $anotherValue);

If, before the

$stmt2 = $database->prepare('INSERT INTO table2 (e, f) VALUES (? ,?)');

I add a simple

$stmt->close();

All works without any problems. So, what is the problem?

You cannot run another query until you have fetched all the results from the previous. Otherwise you will have to make a separate connection.

Did you remember to bind_param & execute ? :

$stmt->bind_param("s", $string);
$stmt->execute();
//etc..

OR

$stmt->bind_param("i", $int);
$stmt->execute();
//etc..

IF you want multiple queries : check out multi_query