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
what are PDO's in PHP?
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
Create a new PDO object:
$pdo = new PDO('dsn', 'username', 'password');
Here:
- 'dsn' (Data Source Name) specifies the database connection details (e.g. database type, host, database name)
- 'username' and 'password' are the credentials to authenticate by the database
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".
Prepare a statement to retrieve the name
Here is the statement for retrieving the specific name of an applicant through database.
$stmt = $pdo->prepare('SELECT name FROM applicants WHERE name = :name');
Bind the parameter:
The specific name you're looking for
$stmt->bindParam(':name', $name);
Set the value of $name
Input the name that you want to search in database
$name = 'Ali Hasan';
Execute query to fetch result
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();
Display the result
Now you have to write the statement to display the result that you have fetched through database
echo $result['name'];
Close the database connection
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.
Top comments (0)