PHP Prepare method not working when calling it twice?

前端 未结 2 541
一生所求
一生所求 2021-01-14 06:58

I am using the prepare method as follows:

$db= new mysqli("localhost","***","***","***");

if ($db->connect_error)          


        
2条回答
  •  天命终不由人
    2021-01-14 07:31

    You need read this: Prepared Statements

    The prepared statement execution consists of two stages: prepare and execute. At the prepare stage a statement template is sent to the database server. The server performs a syntax check and initializes server internal resources for later use.

    and

    Every prepared statement occupies server resources. Statements should be closed explicitly immediately after use. If not done explicitly, the statement will be closed when the statement handle is freed by PHP.

    After reading the article, i concluded: You can not prepare a query, without closing the previous one. Always be prepared to close the inquiry, after the execution.

    And your code should be rewritten as follows:

    $db= new mysqli("localhost","***","***","***");
    if ($db->connect_error) {   
          die('Connection Error'); 
    }
    $id = 1; 
    if($stmt = $db->prepare('SELECT name FROM table WHERE id = ? ')) { 
          $stmt->bind_param('i', $id);   
          $stmt->execute(); 
          echo "Success
    "; } else { echo "Something broke :/
    "; } $id = 2; $stmt->bind_param('i', $id); $stmt->execute(); $stmt->close();

    P.S If you add the check return value of bind and execute - it will be good

提交回复
热议问题