Write a PHP program to connect to a database and create a database with employee table.
Question
Write a PHP program to connect to a database and create a database with employee table.
Solution
Certainly! Here’s a PHP program that connects to a MySQL database and creates a database along with an employee table.
PHP Program
<?php
// Step 1: Database configuration
$servername = "localhost"; // Server name
$username = "your_username"; // Database username
$password = "your_password"; // Database password
// Step 2: Create a connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Step 3: Create a database
$sql = "CREATE DATABASE EmployeeDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
// Step 4: Select the created database
$conn->select_db("EmployeeDB");
// Step 5: Create a table
$sql = "CREATE TABLE Employee (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
email VARCHAR(50),
hire_date DATE,
salary DECIMAL(10, 2)
)";
if ($conn->query($sql) === TRUE) {
echo "Table Employee created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// Step 6: Close the connection
$conn->close();
?>
Instructions:
- Replace
your_username
andyour_password
with your actual database username and password. - Run this script on a server with PHP and MySQL installed (like XAMPP, MAMP, or a live server).
- Upon successful execution, it will create a database named
EmployeeDB
and a table namedEmployee
with predefined columns.
Final Note:
Make sure to handle potential errors and confirmations in a production environment. Always sanitize and prepare your database queries to prevent SQL injections.
Similar Questions
write sql query for the following:1. create database - emp2.create table - employee with 4 columns3.To see table structure
Write a program that would print the information (name, year of joining, salary, address) of threeemployees by creating a class named 'Employee
Create Table Employee with attributes firstName,LastName,SSN,Address,Salary,Birthday,Sex,SupervisorSSN,DepartmentNo
Understand how to interact with databases using PHP (e.g., MySQL, PostgreSQL) through MySQLi or PDO.
In order to create, modify, and gain access to a database, special software, called the database management system, is required.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.