PHP Prepare method not working when calling it twice?

前端 未结 2 515
一生所求
一生所求 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:28

    You need read $stmt->error;

    To read, you need rewrite code as in the example below.

    ...
    $stmt = new mysqli_stmt($db);
    if($stmt->prepare('SELECT name FROM table WHERE id = ? '))
    {
      $stmt->bind_param('i', $id);
      $stmt->execute();
      echo "Success<br>";
    }
    else {
      var_dump($stmt->error);
    }
    ...
    
    0 讨论(0)
  • 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<br>"; 
    } else {   
           echo "Something broke :/<br>"; 
    }
    
    $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

    0 讨论(0)
提交回复
热议问题