libraries:databaseconnector:practicalexamples
Table of Contents
Practical examples
Reading data from a Mysql database
require_once 'DatabaseConnector/DatabaseConnector.php'; $DB = new DatabaseConnector(); // Connection to a MySql database if ($DB->ConnectMysql( 'localhost:8080', 'user1', 'password1', 'database1' ) === FALSE) { // Printing an error message, if an error occured echo 'Connection error: ' . $DB->GetLastError(); } else { $Result = $DB->SqlGetLines('SELECT * FROM tbl_user ORDER BY lastname, firstname'); if ($Result === FALSE) { echo 'Query error: ' . $DB->GetLastError(); } foreach ($Result AS $Row) { echo $Row['lastname'] . ', ' . $Row['firstname'] . ' (born ' . $Row['birthday'] . ')<br>'; } }
Working with transactions
require_once 'DatabaseConnector/DatabaseConnector.php'; $DB = new DatabaseConnector(); // Connection to a MySql database if ($DB->ConnectMysql( 'localhost:8080', 'user1', 'password1', 'database1' ) === FALSE) { // Printing an error message, if an error occured echo 'Connection error: ' . $DB->GetLastError(); } else { // Inserting data within a transaction $DB->TransactionStart(); $bDoCommit = true; foreach ($orderlines AS $Line) { $iOrder = Line['order_id']; $iArticle = Line['article_id']; $iQuant = Line['quantity']; if ($DB->SqlExecute( "INSERT INTO pos (orderid, article, quantity) " . "VALUES ($iOrder, $iArticle, iQuant)" ) === FALSE) { echo 'Insert error: ' . $DB->GetLastError(); $bDoCommit = false; $DB->TransactionRollback(); } } if ($bDoCommit) $DB->TransactionCommit(); }
Working with prepared Statements
require_once 'DatabaseConnector/DatabaseConnector.php'; $DB = new DatabaseConnector(); $USERSESSION = ''; // Connection to a MySql database if ($DB->ConnectMysql( 'localhost:8080', 'user1', 'password1', 'database1' ) === FALSE) { // Printing an error message, if an error occured echo 'Connection error: ' . $DB->GetLastError(); } else { // Example 1 - Working with unnamed placeholders ------------------------------- // Preparing a statement for getting a user's session id by // username and passwort sent with a POST-Request $DB->SqlPrepareStatement("SELECT session FROM tbl_users WHERE LOWER(username) = ? AND password = ?"); $Result = $DB->SqlGetPreparedLines( array($_POST['username'], $_POST['password']) ); // Example 2 - Working with named placeholders ------------------------------- // Preparing a statement for getting a user's session id by // username and passwort sent with a POST-Request $DB->SqlPrepareStatement("SELECT session FROM tbl_users WHERE LOWER(username) = :user AND password = :pass"); $Result = $DB->SqlGetPreparedLines( array('user' => $_POST['username'], 'pass' => $_POST['password']) ); if ($Result === FALSE) { echo 'Authentification error: ' . $DB->GetLastError(); } else { $USERSESSION = $Result['session']; // [...] } }
libraries/databaseconnector/practicalexamples.txt · Last modified: 2023/03/31 19:27 by michael.pohl