PHP code example of fractalizer / php-sweet-pdo

1. Go to this page and download the library: Download fractalizer/php-sweet-pdo library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

fractalizer / php-sweet-pdo example snippets




necting
$connection = new \phpSweetPDO\Connection('mysql:dbname=test;host=127.0.0.1', 'root', 'password');

//Executing DDL
$connection->execute("DROP TABLE IF EXISTS `phpsweetpdo`");

//Selecting only one value
$value = $connection->getOneValue("SELECT field2 FROM phpsweetpdo WHERE id=? AND field2 <> ?", array(1, 300));
echo $value;

//Selecing only one row
$record = $connection->getOneRow("SELECT * FROM phpsweetpdo WHERE id=:id1 AND field2<>:id2",
                                                 array('id1' => 1, 'id2' => 300));
echo $record->field1 . $record->field2; //Will throw exception if fields do not exist in a row

//Selecting more than 1 row
$recordset = $connection->select("SELECT * FROM phpsweetpdo ORDER BY field1 ASC");
foreach ($recordset as $currentRow) {
    echo $currentRow->id; //Will throw exception if field id does not exist in recordset
}

//Output parameters of stored procedures
$connection->execute("CALL phpsweetpdo_out(@test)");
$result = $connection->getOneValue("SELECT @test");

//INSERT and UPDATE build helpers
use phpSweetPDO\SQLHelpers\Basic as Helpers;
$sql = Helpers::insert('mytable', array('field_name' => 'field_value'));
$connection->execute($sql); // INSERT INTO mytable (field_name) VALUES (:field_name); //:field_name = 'field_value'

$sql = Helpers::update('mytable', array('field_name' => 'field_value'), "field_2=13");
$connection->execute($sql); // UPDATE test SET field_name=:field_name WHERE field_2='13'; //:field_name = 'field_value'



function onEvent(\phpSweetPDO\Events\DbEvent $event) {
    echo $event->getName();
    $params = $event->getParameters();
    echo 'SQL query is ' . $params['sql'];
}

$eventDispatcher = new \Symfony\Component\EventDispatcher\EventDispatcher();
$eventDispatcher->addListener('phpsweetpdo.select.started', 'onEvent');
$eventDispatcher->addListener('phpsweetpdo.select.finished', 'onEvent');

$connection = new \phpSweetPDO\Connection('mysql:dbname=test;host=127.0.0.1', 'root', '', $eventDispatcher);
$connection->select("SELECT * FROM phpsweetpdo ORDER BY field1 ASC");
//At this point our onEvent() function will be called twice with respected events and will print the query,
//we tried to execute.