PHP Basics on Ubuntu

Mercy Jemosop
6 min readJan 16, 2023

--

Introduction to PHP

Introduction

PHP stands for Hypertext Preprocessor. It is a general-purpose scripting language that is especially suited to web development.

PHP tags, when PHP parses a file it looks for an opening and closing tags <?php and ?>. These tags will tell PHP to start and stop interpreting the code between them.

Parsing in programming means analyzing and converting a program into an internal format that a runtime environment can actually run.

N.B Install PHP, Xampp

Check the PHP version to verify it is installed on your computer.

php --version

Check if Xampp is installed

Open Xampp, start the server you need, in this case I started all. To check the server port. Click the configure button on the right, a pop up with the port will show.

To open xampp, type the command below on your browser, 80 is my xampp port. You open Xampp dashboard on your browser using the command below. It will redirect to http://localhost/dashboard/ or you can just run localhost/dashboard/

localhost:80

If you have not given htdocs directory permission in Xampp. Run the command below to be able to create a project in htdocs. In Ubuntu, Xampp was installed in /opt/lampp/. Navigate to that path and run the command below to be able to create a project inside htdocs.

sudo chmod 777 -R htdocs

Create a PHP Project

In windows

1. Navigate to the C directory

2. Search for Xampp folder, navigate to htdocs inside xampp

3. Create your project inside htdocs

4. open your project using vscode, sublimetext or any editor

In Ubuntu

  1. Navigate to htdocs directory
cd opt/lampp/htdocs

2. To open that directory type the command below on your path above. You will get a pop up of the contents of htdocs directory

nautilus .

3. Create a folder/ directory i.e hello_php

4. Open the project in vscode by right clicking on the folder you created and using open with option. You can also use any other method which will work for you.

Let’s start by displaying “hello world”

  1. Create a file e.g index.php, inside the folder you created above
  2. From our intro, php code should have both closing and opening tags. We will use “echo” to display the text.

3. To check the changes on the browser

http://localhost/hello_php/index.php

4. You will get the text above in your browser.

Congratulations!!!!!!!. If you have not reached this part, go over your steps and research on where you might have gone wrong.

Database Connection

Navigate to the dashboard by typing http://localhost/dashboard/ on your browser. You should see the page below. Click phpMyAdmin or You can just search http://localhost/phpmyadmin/

Database Structure

Create a database by clicking new and adding the database name. I created a database called school . You can give your database a different name.

Connect with database using PHP

#Your database credentials, my username and password are the default
#You can change the username and password, change the database name to match
#the one you created

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "school";

Create a new connection to Database/MySQL server

$conn = mysqli_connect($servername, $username, $password,$dbname);

Check server connection and display error on success

// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

Complete code

Create a database_connection.php

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "school";

// Create connection
$conn = mysqli_connect($servername, $username, $password,$dbname);

// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
echo "Connected successfully \n";
$conn->close();
?>

Include the file database_connection.php in index.php

<?php
include("database_connection.php");
echo "Hello World";
?>

Restart your browser and you will get the text below

Connected successfully Hello World 

Insert Data into a table in the Database

  1. Create a table inside the school(your DB ), my table name is “school”
  2. I have two fields: id, auto-increment and name.

Insert data into student table

Create a file named save_student.php

  1. Add headers to the file

The header() function sends a raw HTTP header to a client. It is declared before any actual output is sent

syntax

header(header, replace, http_response_code)

  header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With');$data = json_decode(file_get_contents("php://input"), true);

json_decode() function is used to decode or convert a JSON object to a PHP object.

file_get_contents — Reads entire file into a string.

Insert the data into the student table, student_name field using the sql query.

$data = json_decode(file_get_contents("php://input"), true);    $sname = $data['student_name'];
include 'database_connection.php';
$sql = "insert into student (student_name) values ('$sname')";

The include or require statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.

    $sname = $data['student_name'];
include 'database_connection.php';
$sql = "insert into student (student_name) values ('$sname')";

Complete save_student.php

<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With');

$data = json_decode(file_get_contents("php://input"), true);

$sname = $data['student_name'];

include 'database_connection.php';

$sql = "insert into student (student_name) values ('$sname')";

if (mysqli_query($conn, $sql)) {
echo json_encode(['msg' => 'Data Inserted Successfully!', 'status' => true]);
} else {
echo json_encode(['msg' => 'Data Failed to be Inserted!', 'status' => false]);
}
?>

Test the data using postman

Postman is an API(application programming interface) development tool which helps to build, test and modify APIs. Almost any functionality that could be needed by any developer is encapsulated in this tool. It is used by over 5 million developers every month to make their API development easy and simple.

Update Username

Create a file named update_student.php

When updating data in the database, we use the update sql statement, find the id of the record you need to update and set the field you need to change to the new field.

<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: PUT');
header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With');

$data = json_decode(file_get_contents("php://input"), true);

$sname = $data['student_name'];
$sid = $data['id'];

include 'database_connection.php';

$sql = "update student set student_name = '$sname' where id = '$sid'";

if (mysqli_query($conn, $sql)) {
echo json_encode(['msg' => 'Data Updated Successfully!', 'status' => true]);
} else {
echo json_encode(['msg' => 'Data Failed to be Updated!', 'status' => false]);
}
?>

Fetch Records from Database

You can get a list of all students or search a student by name

// header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

$data = json_decode(file_get_contents("php://input"), true);

$searchterm = $data['student_name'];

include 'database_connection.php';

$sql = "select * from student where student_name like '%$searchterm%'";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($data);
} else {
echo json_encode(['msg' => 'No Data Found to search query!', 'status' => false]);
}

postman

Delete Student

<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: DELETE');
header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Authorization, X-Requested-With');

$data = json_decode(file_get_contents("php://input"), true);

$sid = $data['id'];

include 'database_connection.php';

$sql = "delete from student where id = '$sid'";

if (mysqli_query($conn, $sql)) {
echo json_encode(['msg' => 'Data Deleted Successfully!', 'status' => true]);
} else {
echo json_encode(['msg' => 'Data Failed to be Deleted!', 'status' => false]);
}
?>

I hope this article has helped you get a basic grasp of PHP and MySQL connection. You can pass the endpoint to react, vue or the UI you need to integrate and do more practice.

Happy coding!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1

Sources: w3school, beproblemsolver, youtube

Github: hello_php

--

--

Mercy Jemosop

Software Developer. I am open to job referrals. connect with me on twitter @kipyegon_mercy