phpsqlitepdo

Do I need to prepare statement on every open or can prepare only once in PDO PHP SQLite3


I found this example on net for inserting in SQLite usong PHP PDO

# no placeholders - ripe for SQL Injection!  
$STH = $DBH->("INSERT INTO folks (name, addr, city) values ($name, $addr, $city)");  

# unnamed placeholders  
$STH = $DBH->("INSERT INTO folks (name, addr, city) values (?, ?, ?); 

# named placeholders 
$STH = $DBH->("INSERT INTO folks (name, addr, city) value (:name, :addr, :city)"); 

I am closing connection after every command ( another app only reads and mine only inserts). Do I need to prepare statement on every open or can prepare only once ?


Solution

  • prepared statements need to be prepared once per connection, here is an example:

    $userprep = $userdbc->prepare("
        INSERT INTO Users (userID, userPass, userName, userEmail)
        VALUES (:userID, :userPass, :userName, :userEmail)
    ");
    $userprep->execute($newUser);
    

    here is an example of my code to insert a new user using placeholders..

    $newUser is an associative array.

    once you have prepared a statement you can execute that statement as many times as you wish, for example if i had a nested array of users to enter i could just run this:

    for($i = 0; $i < count($newUser); $i++){
        $userprep->execute($newUser[$i]);
    }
    

    (the nested arrays would have to of course use associative keys)

    Hope this is of some help..