|
|
|
Re: How create a PDT connection to mysql database [message #1821525 is a reply to message #1819598] |
Fri, 14 February 2020 06:39 |
Tell Media Messages: 1 Registered: February 2020 |
Junior Member |
|
|
first, you have to need to add all necessary driver and load or add a driver to project library after write code given below
PDO data base connection and INSERT , UPDATE AND DELETE QUERY
connecting to MySQL database:
<?php
# Connect
mysql_connect('localhost', 'database_user', 'database_password') or die('Could not connect: ' . mysql_error());
?>
//If there is an error in database connection how can we identify so here is try/catch for error handling.
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=myDB', $db_username, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
PDO::ERRMODE_EXCEPTION will fire exceptions when occur. Using this procedure we can handle any exception.
There is two ways to fetch data query and execute we explain both.
////1. Query
<?php
$string = 'PHPGang'; # user submitted data
try {
#connection
$conn = new PDO('mysql:host=localhost;dbname=myDB', $db_username, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->query('SELECT * FROM myTable WHERE name = ' . $conn->quote($string)); // $conn->quote used to protect SQL injection
foreach($data as $rows) {
print_r($rows);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
|
|
|
Powered by
FUDForum. Page generated in 0.03028 seconds