Php PDO: Prepared Statement


Prepare statement is the method of Php PDO.
The prepare() statement is used to build the query while we are using Php PDO.

Once the prepare statement is declared with query then The values in  that query is passed  as array format using execute method of PDO. The example below shows the use of prepare statement in Php PDO.

Example :

<?php
    // database connection
    $connection = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

    $title = 'echonomic%';
    $author = 'Hiren%';
    // query
    $sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
    $query = $connection->prepare($sql);


    //Now passsing the variables to query and execute it
    $query->execute(array($title,$author));    
    query->setFetchMode(PDO::FETCH_BOTH);

    // fetch
    while ($result = query->fetch()) {
       print_r($result);
     }
?>

In the above example, query depends on a variabel (?).
This script will output the books which has title starts with echonomics and author starts with Hiren.

Click to view More Examples using PDO prepare() statement.

Note : Php Extension for mysql and SQLite does not support this kind of functionality.

1 comment:

Unknown said...

Thanks For your Information. Webwing Technologies Is also Provide IT Services.Hope this can also be use full to you.
Hire PHP developer in India