Friday, October 16, 2020

, ,

Install and configure your local server to test PHP application and PHP based content management system
( Part-3: Connect database from PHP application )

 

To connect our MySql database which was created earlier in Part-2,  let's create a folder inside www folder of WampServer installation folder D:\wamp64 and give the name user-management-system  and create a new PHP file named connection.php. The WampServer installation process was described in Part-1 if this Tutorial. For this entire tutorial we will create our all PHP files inside this folder.



connection.php


<?php

define('MYSQLSERVER','localhost'); // Our Database Server Host
define('MYSQLSERVER_USERNAME','solocoding'); // Database Username
define('MYSQLSERVER_PASSWORD','mypassword'); // Database password
define('MYSQLSERVER_DATABASE','myFirstDatabase'); // Database we have created in Part-2 of this tutorial

// Connection string
$dbc = mysqli_connect(MYSQLSERVER, MYSQLSERVER_USERNAME, MYSQLSERVER_PASSWORD, MYSQLSERVER_DATABASE);

// Test the Database Connection
if($dbc === false)
{
die("Error: " . mysqli_connect_error());
}
else
{
echo("Connection Successful!");
}

?>

Let's test our connection.php file. To run connection.php file, start WampServer and let the icon it be green shown in notification area. Open your web browser and type the following address in address bar:

http://localhost/user-management-system/connection.php

If everything is OK, you will get the following output.  Connection Successful!


Let's read our userlogin table and display all the records. For that create another file named showrecord.php. and copy the following code in it.

showrecord.php

<?php
require_once "connection.php";

$sql = 'SELECT * FROM userlogin';
$retval = $dbc->query($sql);

if(! $retval ) {
die('Could not get data: ' . mysqli_error());
}
else{
echo
"<br />Data read from table userlogin table: <br />".
"----------------------------------------------------<br>";
while($row = $retval->fetch_assoc()) {
echo
"ID :{$row['id']} <br /> ".
"User Name: {$row['username']} <br /> ".
"Email : {$row['email']} <br /> ".
"Password : {$row['password']} <br /> ".
"Created at : {$row['created_at']} <br />".
"----------------------------------------------------<br>";
}
echo "Fetched data Completed\n";
}
$retval->free();
$dbc->close();
?>

Let's run the above PHP file by typing http://localhost/user-management-system/showrecord.php in browser's address bar. 


 In this Part we have successfully read all data from our database table. In Part-4 of this tutorial we will learn how to insert, update and delete records in userlogin table by using PHP.

Read Part-2






Share:

0 comments:

Post a Comment