XAMPP is an open source package that contains Apache, PHP and many PHP 'extensions'. One of these extension is PHP OCI8 which connects to Oracle Database
Visit http://localhost/dashboard/phpinfo.php via your browser to see the architecture and thread safety mode of the installed PHP. Please note this is the architecture of the installed PHP and not the architecture of your machine. It’s possible to run a x86 PHP on an x64 machine.
Oracle OCI8 is pre-installed in XAMPP but if you need a newer version you can download an updated OCI8 PECL package from pecl.php.net. Pick an OCI8 release and select the DLL according to the architecture and thread safety mode. For example, if PHP is x86 and thread safety enabled, download "7.2 Thread Safe (TS) x86". Then replace "D:\xampp\php\ext\php_oci8_12c.dll" with the new "php_oci8_12c.dll" from the OCI8 PECL package.
Edit "D:\xampp\php\php.ini" and uncomment the line "extension=oci8_12c". Make sure "extension_dir" is set to the directory containing the PHP extension DLLs. For example
extension=D:\xampp_726\php\ext\php_oci8.dll
Download the Oracle Instant Client Basic package from OTN. and Select the correct architecture to align with PHP's. For Windows x86 download "instantclient-basic-nt-12.2.0.1.0.zip" from the Windows 32-bit page.
Extract the file in a directory such as "D:\Oracle". A subdirectory "D:\Oracle\instantclient_12_2" will be created. Add this subdirectory to the PATH environment variable. You can update PATH in Control Panel -> System -> Advanced System Settings -> Advanced -> Environment Variables -> System Variables -> PATH. In my example I set it to "D:\Oracle\instantclient_12_2".
Restart the Apache server and check the phpinfo.php page again. It shows the OCI8 extension is loaded successfully.
If you also run PHP from a terminal window, make sure to close and reopen the terminal to get the updated PATH value.
To run your first OCI8 application, create a new file in the XAMPP document root "D:\xampp\htdocs\test.php". It should contain:
<?php error_reporting(E_ALL); ini_set('display_errors', 'On'); $username = "hr"; // Use your username $password = "welcome"; // and your password $database = "localhost/orclpdb"; // and the connect string to connect to your database $query = "select * from dual"; $c = oci_connect($username, $password, $database); if (!$c) { $m = oci_error(); trigger_error('Could not connect to database: '. $m['message'], E_USER_ERROR); } $s = oci_parse($c, $query); if (!$s) { $m = oci_error($c); trigger_error('Could not parse statement: '. $m['message'], E_USER_ERROR); } $r = oci_execute($s); if (!$r) { $m = oci_error($s); trigger_error('Could not execute statement: '. $m['message'], E_USER_ERROR); } echo "<table border='1'>\n"; $ncols = oci_num_fields($s); echo "<tr>\n"; for ($i = 1; $i <= $ncols; ++$i) { $colname = oci_field_name($s, $i); echo " <th><b>".htmlspecialchars($colname,ENT_QUOTES|ENT_SUBSTITUTE)."\n"; } echo "\n"; while (($row = oci_fetch_array($s, OCI_ASSOC+OCI_RETURN_NULLS)) != false) { echo "\n"; foreach ($row as $item) { echo " "; echo $item!==null?htmlspecialchars($item, ENT_QUOTES|ENT_SUBSTITUTE):" "; echo "</td>\n"; } echo "</tr>\n"; } echo "</table>\n"; ?> PHP to MySql database connection
PHP 5 and later can work with a MySQL database using:
- MySQLi extension (the "i" stands for improved)
- PDO (PHP Data Objects)
Should I Use MySQLi or PDO?
Both MySQLi and PDO have their advantages:
PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases.
So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries. With MySQLi, you will need to rewrite the entire code - queries included.
Both are object-oriented, but MySQLi also offers a procedural API.
Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very important for web application security.
In this, and in the following chapters we demonstrate three ways of working with PHP and MySQL:
- MySQLi (object-oriented)
- MySQLi (procedural)
- PDO
Enable the following libray in xampp server
extension=php_mysqli.dll extension=php_pdo.dllOpen a Connection to MySQL
by MySQLi Object-Oriented$servername = "localhost"; $username = "username"; $password = "password"; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; // Create database $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: " . $conn->error; } // sql to create table $sql = "CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; if ($conn->query($sql) === TRUE) { echo "Table MyGuests created successfully"; } else { echo "Error creating table: " . $conn->error; } // single $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if ($conn->query($sql) === TRUE) { $last_id = $conn->insert_id; echo "New record created successfully"; } else { echo "Error: " . $sql . "by MySQLi Procedural
" . $conn->error; } // multiple $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"; if ($conn->multi_query($sql) === TRUE) { echo "New records created successfully"; } else { echo "Error: " . $sql . "
" . $conn->error; } // prepare and bind $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"); $stmt->bind_param("sss", $firstname, $lastname, $email); // set parameters and execute $firstname = "John"; $lastname = "Doe"; $email = "john@example.com"; $stmt->execute(); $firstname = "Mary"; $lastname = "Moe"; $email = "mary@example.com"; $stmt->execute(); $firstname = "Julie"; $lastname = "Dooley"; $email = "julie@example.com"; $stmt->execute(); echo "New records created successfully"; // select data $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
"; } } else { echo "0 results"; } // sql to delete a record $sql = "DELETE FROM MyGuests WHERE id=3"; if ($conn->query($sql) === TRUE) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . $conn->error; } // update data $sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } $conn->close();$servername = "localhost"; $username = "username"; $password = "password"; // Create connection $conn = mysqli_connect($servername, $username, $password); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; // Create database $sql = "CREATE DATABASE myDB"; if (mysqli_query($conn, $sql)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysqli_error($conn); } // sql to create table $sql = "CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; if (mysqli_query($conn, $sql)) { echo "Table MyGuests created successfully"; } else { echo "Error creating table: " . mysqli_error($conn); } // single $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if (mysqli_query($conn, $sql)) { $last_id = mysqli_insert_id($conn); echo "New record created successfully"; } else { echo "Error: " . $sql . "by PDO
" . mysqli_error($conn); } // multiple $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"; if (mysqli_multi_query($conn, $sql)) { echo "New records created successfully"; } else { echo "Error: " . $sql . "
" . mysqli_error($conn); } // prepare and bind $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"); $stmt->bind_param("sss", $firstname, $lastname, $email); // set parameters and execute $firstname = "John"; $lastname = "Doe"; $email = "john@example.com"; $stmt->execute(); $firstname = "Mary"; $lastname = "Moe"; $email = "mary@example.com"; $stmt->execute(); $firstname = "Julie"; $lastname = "Dooley"; $email = "julie@example.com"; $stmt->execute(); echo "New records created successfully"; // select data $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
"; } } else { echo "0 results"; } // sql to delete a record $sql = "DELETE FROM MyGuests WHERE id=3"; if (mysqli_query($conn, $sql)) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($conn); } // update data $sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; if (mysqli_query($conn, $sql)) { echo "Record updated successfully"; } else { echo "Error updating record: " . mysqli_error($conn); } mysqli_close($conn);$servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; $sql = "CREATE DATABASE myDBPDO"; // use exec() because no results are returned $conn->exec($sql); echo "Database created successfully
"; // sql to create table $sql = "CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; // use exec() because no results are returned $conn->exec($sql); echo "Table MyGuests created successfully"; // single $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; // use exec() because no results are returned $conn->exec($sql); $last_id = $conn->lastInsertId(); echo "New record created successfully"; // multiple // begin the transaction $conn->beginTransaction(); // our SQL statements $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"); $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com')"); $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"); // commit the transaction $conn->commit(); echo "New records created successfully"; // prepare sql and bind parameters $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (:firstname, :lastname, :email)"); $stmt->bindParam(':firstname', $firstname); $stmt->bindParam(':lastname', $lastname); $stmt->bindParam(':email', $email); // insert a row $firstname = "John"; $lastname = "Doe"; $email = "john@example.com"; $stmt->execute(); // insert another row $firstname = "Mary"; $lastname = "Moe"; $email = "mary@example.com"; $stmt->execute(); // select data $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows > 0) { echo "<table><tr><th>ID</th><th>Name</th></tr>"; // output data of each row while($row = $result->fetch_assoc()) { echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td></tr>"; } echo "</table>"; } else { echo "0 results"; } // sql to delete a record $sql = "DELETE FROM MyGuests WHERE id=3"; // use exec() because no results are returned $conn->exec($sql); echo "Record deleted successfully"; } catch(PDOException $e) { echo $sql . "
" . $e->getMessage(); } // update data $sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; // Prepare statement $stmt = $conn->prepare($sql); // execute the query $stmt->execute(); // echo a message to say the UPDATE succeeded echo $stmt->rowCount() . " records UPDATED successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); }Limit Data Selections From a MySQL Database
Assume we wish to select all records from 1 - 30 (inclusive) from a table called "Orders". The SQL query would then look like this:
$sql = "SELECT * FROM Orders LIMIT 30";What if we want to select records 16 - 25 (inclusive)?
Mysql also provides a way to handle this: by using OFFSET.
The SQL query below says "return only 10 records, start on record 16 (OFFSET 15)":
$sql = "SELECT * FROM Orders LIMIT 10 OFFSET 15"; or $sql = "SELECT * FROM Orders LIMIT 15, 10";Open a Connection to SQLite
by PDOSQLite is bundled with the scripting language. This is a lightweight, file-based database. That allows very fast reading (in many cases, even faster than when using a "real" database), but writing can sometimes take longer than with other systems because file locking is an issue.
$myPDO = new PDO('sqlite:/home/username/path/filename'); //For example, if you have a SQLite database named books.db in your home directory, and your username is example, you would use the following statement: $myPDO = new PDO('sqlite:/home/example/books.db'); $result = $myPDO->query("SELECT lastname FROM employees"); foreach($result as $row) { print $row['lastname'] . "\n"; }MongoDB(NoSql)
Enable library
extension = php_mongo.dllPHP to MongoDB Connection// connect to mongodb $m = new MongoClient(); echo "Connection to database successfully"; // select a database $db = $m->mydb; // or $db = new MongoClient("mongodb://testUser:testPass@localhost:myportnumber"); $db = new MongoClient('mongodb://localhost', [ 'username' => 'abc', 'password' => 'abc@123', 'db' => 'mydb' ]); echo "Database mydb selected"; //Create a Collection $collection = $db->createCollection("mycol"); echo "Collection created succsessfully"; //Insert a Document $collection = $db->mycol; echo "Collection selected succsessfully"; $document = array( "title" => "MongoDB", "description" => "database", "likes" => 100, "url" => "http://www.tutorialspoint.com/mongodb/", "by" => "tutorials point" ); $collection->insert($document); echo "Document inserted successfully"; //Find All Documents $cursor = $collection->find(); // iterate cursor to display title of documents foreach ($cursor as $document) { echo $document["title"] . "\n"; } //Update a Document $collection->update(array("title"=>"MongoDB"), array('$set'=>array("title"=>"MongoDB Tutorial"))); echo "Document updated successfully"; // now display the updated document $cursor = $collection->find(); // iterate cursor to display title of documents echo "Updated document"; foreach ($cursor as $document) { echo $document["title"] . "\n"; } // now remove the document $collection->remove(array("title"=>"MongoDB Tutorial"),false); echo "Documents deleted successfully"; // now display the available documents $cursor = $collection->find(); // iterate cursor to display title of documents echo "Updated document"; foreach ($cursor as $document) { echo $document["title"] . "\n"; }Open a Connection to mariadb(file base database )
$dbhost = 'localhost:3036'; $dbuser = 'guest1'; $dbpass = 'guest1a'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; // create database $sql = 'CREATE DATABASE PRODUCTS'; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not create database: ' . mysql_error()); } echo "Database PRODUCTS created successfully\n"; // drop database $sql = 'DROP DATABASE PRODUCTS'; $retval = mysql_query( $sql, $conn ); if(! $retval ){ die('Could not delete database: ' . mysql_error()); } echo "Database PRODUCTS deleted successfully\n"; // select database mysql_select_db( 'PRODUCTS' ); // create table $sql = "CREATE TABLE products_tbl( ". "product_id INT NOT NULL AUTO_INCREMENT, ". "product_name VARCHAR(100) NOT NULL, ". "product_manufacturer VARCHAR(40) NOT NULL, ". "submission_date DATE, ". "PRIMARY KEY ( product_id )); "; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not create table: ' . mysql_error()); } echo "Table created successfully\n"; // drop table $sql = "DROP TABLE products_tbl"; mysql_select_db( 'PRODUCTS' ); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not delete table: ' . mysql_error()); } echo "Table deleted successfully\n"; //insert data if(! get_magic_quotes_gpc() ) { $product_name = addslashes ($_POST['product_name']); $product_manufacturer = addslashes ($_POST['product_name']); } else { $product_name = $_POST['product_name']; $product_manufacturer = $_POST['product_manufacturer']; } $ship_date = $_POST['ship_date']; $sql = "INSERT INTO products_tbl ". "(product_name,product_manufacturer, ship_date) ". "VALUES"."('$product_name','$product_manufacturer','$ship_date')"; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } echo "Entered data successfully\n"; // select data $sql = 'SELECT product_id, product_name,product_manufacturer, ship_date FROM products_tbl'; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not get data: ' . mysql_error()); } while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { echo "Product ID :{$row['product_id']} <br> ". "Name: {$row['product_name']} <br> ". "Manufacturer: {$row['product_manufacturer']} <br> ". "Ship Date : {$row['ship_date']} <br>". "--------------------------------<br>"; } // or while($row = mysql_fetch_array($retval, MYSQL_NUM)) { echo "Product ID :{$row[0]} <br> ". "Name: {$row[1]} <br> ". "Manufacturer: {$row[2]} <br> ". "Ship Date : {$row[3]} <br> ". "--------------------------------<br>"; } mysql_free_result($retval); echo "Fetched data successfully\n"; // update data $sql = ‘UPDATE products_tbl SET product_name = ”Fiber Blaster 300z” WHERE product_id = 112’; mysql_select_db(‘PRODUCTS’); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die(‘Could not update data: ‘ . mysql_error()); } echo “Updated data successfully\n”; // delete data $sql = 'DELETE FROM products_tbl WHERE product_id = 261'; mysql_select_db('PRODUCTS'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not delete data: ' . mysql_error()); } echo "Deleted data successfully\n"; mysql_close($conn);Open a Connection to postgreeSql
$host = "host = 127.0.0.1"; $port = "port = 5432"; $dbname = "dbname = testdb"; $credentials = "user = postgres password=pass123"; $db = pg_connect( "$host $port $dbname $credentials" ); if(!$db) { echo "Error : Unable to open database\n"; } else { echo "Opened database successfully\n"; } // create a table $sql =<<<EOF CREATE TABLE COMPANY (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL); EOF; $ret = pg_query($db, $sql); if(!$ret) { echo pg_last_error($db); } else { echo "Table created successfully\n"; } // INSERT Operation $sql =<<<EOF INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Teddy', 23, 'Norway', 20000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 ); EOF; $ret = pg_query($db, $sql); if(!$ret) { echo pg_last_error($db); } else { echo "Records created successfully\n"; } // SELECT Operation $sql =<<<EOF SELECT * from COMPANY; EOF; $ret = pg_query($db, $sql); if(!$ret) { echo pg_last_error($db); exit; } while($row = pg_fetch_row($ret)) { echo "ID = ". $row[0] . "\n"; echo "NAME = ". $row[1] ."\n"; echo "ADDRESS = ". $row[2] ."\n"; echo "SALARY = ".$row[4] ."\n\n"; } echo "Operation done successfully\n"; // UPDATE Operation $sql =<<<EOF UPDATE COMPANY set SALARY = 25000.00 where ID=1; EOF; $ret = pg_query($db, $sql); if(!$ret) { echo pg_last_error($db); exit; } else { echo "Record updated successfully\n"; } $sql =<<<EOF SELECT * from COMPANY; EOF; $ret = pg_query($db, $sql); if(!$ret) { echo pg_last_error($db); exit; } while($row = pg_fetch_row($ret)) { echo "ID = ". $row[0] . "\n"; echo "NAME = ". $row[1] ."\n"; echo "ADDRESS = ". $row[2] ."\n"; echo "SALARY = ".$row[4] ."\n\n"; } echo "Operation done successfully\n"; // DELETE Operation $sql =<<<EOF DELETE from COMPANY where ID=2; EOF; $ret = pg_query($db, $sql); if(!$ret) { echo pg_last_error($db); exit; } else { echo "Record deleted successfully\n"; } $sql =<<<EOF SELECT * from COMPANY; EOF; $ret = pg_query($db, $sql); if(!$ret) { echo pg_last_error($db); exit; } while($row = pg_fetch_row($ret)) { echo "ID = ". $row[0] . "\n"; echo "NAME = ". $row[1] ."\n"; echo "ADDRESS = ". $row[2] ."\n"; echo "SALARY = ".$row[4] ."\n\n"; } echo "Operation done successfully\n"; pg_close($db);Latest TutorialMost Viewed TutorialbONEandALLVisitorTotal : 26654
Today :3
Today Visit Country :
- France
- United States