As I learned last time, how to create database using query in terminal.
mysql -uroot /*Press enter key and then give input to terminal to create database.*/ create database myapp;
Now, I need to connect to the database so I can access the table and fetch the specific name.
To connect to the database, you'll need to use PHP code to establish a connection using PDO (PHP Data Objects) or mysqli (MySQL Improved Extension). Here's an example using PDO, firstly we have to know about PDO
PDO (PHP Data Objects) is a PHP extension that provides a consistent interface for accessing and manipulating databases.
Here are some basic steps to get database accessible and to retrieve data
$pdo = new PDO('dsn', 'username', 'password');
Here:
Example:
$pdo=newPDO('mysql:host=localhost;dbname=myapp', 'root', 'password');
This creates a connection to a MySQL database named "myapp" on the local host with the username "root" and password "password".
Here is the statement for retrieving the specific name of an applicant through database.
$stmt = $pdo->prepare('SELECT name FROM applicants WHERE name = :name');
The specific name you're looking for
$stmt->bindParam(':name', $name);
Input the name that you want to search in database
$name = 'Ali Hasan';
After inputing the name in $name variable then next step is execution of statement. As the execution is completed then fetch the result
$stmt->execute(); $result = $stmt->fetch();
Now you have to write the statement to display the result that you have fetched through database
echo $result['name'];
At the end of search you have to close the connection through database using PDO variable with null value.
$pdo = null;
I hope that you have understand it completely.
The above is the detailed content of How to create a database and access specific data from it?. For more information, please follow other related articles on the PHP Chinese website!