Skip to main content

What is INNER JOIN in MySQL and how to use with PHP?

 







Database structure of practical Example:

-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jan 28, 2025 at 01:20 PM
-- Server version: 10.4.32-MariaDB
-- PHP Version: 8.2.12

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `mytest`
--

-- --------------------------------------------------------

--
-- Table structure for table `categories`
--

CREATE TABLE `categories` (
  `category_id` int(11) NOT NULL,
  `category_name` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `categories`
--

INSERT INTO `categories` (`category_id`, `category_name`) VALUES
(1, 'Samsung'),
(2, 'Apple'),
(3, 'Nokia');

-- --------------------------------------------------------

--
-- Table structure for table `products`
--

CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `product_name` varchar(100) NOT NULL,
  `unit_price` int(11) NOT NULL,
  `unit_in_stock` int(11) NOT NULL,
  `category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `product_name`, `unit_price`, `unit_in_stock`, `category_id`) VALUES
(1, 'Samsung tx-30', 10500, 20, 1),
(2, 'Samsung red-40', 11200, 25, 1),
(3, 'Samsung blue-55', 25000, 15, 1),
(4, 'Nokia star-tz', 15000, 12, 3),
(5, 'Nokia tiptop', 16000, 26, 3),
(6, 'Apple mega4', 160000, 10, 2),
(7, 'Apple superX', 200000, 24, 2);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `categories`
--
ALTER TABLE `categories`
  ADD PRIMARY KEY (`category_id`);

--
-- Indexes for table `products`
--
ALTER TABLE `products`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `categories`
--
ALTER TABLE `categories`
  MODIFY `category_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;

--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Practical Example 1:index1.php code


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
body{
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}


table{
border-collapse: collapse;
width:50%;
}

h2{
color:red;
font-weight: bold;
}
</style>
<title>INNER JOIN</title>
</head>
<body>

<?php
$_GET['category'] = 2;
// Parse the query string
 if (isset($_GET['category'])) {
 $category_num = $_GET['category'];
 } else {
  echo 'The "category" parameter is missing!<br>';
    echo 'We are done here, sorry.';
 exit(0);


 }

 // Store the database connection parameters
 $host = 'localhost';
 $user = 'root';
 $password = '';
 $database = 'mytest';

 // create a new mysqli object with the database connection
 $mysqli = new mysqli($host, $user, $password, $database);

 // create select query
 $sql = "SELECT products.product_name,
 products.unit_price,
 products.unit_in_stock,
 categories.category_name
 FROM products
 INNER JOIN categories
 ON products.category_id = categories.category_id
 WHERE products.category_id = $category_num";
  $result = $mysqli->query($sql);
 $result2 = $mysqli->query($sql);
 $Category = $result2->fetch_array();
 ?>



 <h2>Product Category:<?php echo $Category['category_name']; ?> </h2>



  

 <table border="1">
  <thead>
  <tr>
  <th>Products </th>
  <th>Unit Price </th>
  <th>Stock Units </th>
  </tr>
  </thead>
  <tbody>


 <?php

 // Get the query result

 while($rows = $result->fetch_assoc()){?>
       <tr>
      <td><?php echo $rows['product_name']; ?> </td>
      <td><?php echo $rows['unit_price']; ?> </td>
      <td><?php echo $rows['unit_in_stock']; ?> </td>
       </tr>
<?php
 }

 

 




?>

</tbody>

</table>

</body>
</html>
 
Application Output:
Practical Example 2:index2.php

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">

body{
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}


table{
border-collapse: collapse;
width:50%;
}

h2{
color:red;
font-weight: bold;
}
</style>
<title>INNER JOIN</title>
</head>
<body>

<?php
// $_GET['category'] = 2;
// // Parse the query string
 // if (isset($_GET['category'])) {
 // $category_num = $_GET['category'];
 // } else {
 // echo 'The "category" parameter is missing!<br>';
 //    echo 'We are done here, sorry.';
 // exit(0);


 // }

 // Store the database connection parameters
 $host = 'localhost';
 $user = 'root';
 $password = '';
 $database = 'mytest';

 // create a new mysqli object with the database connection
 $mysqli = new mysqli($host, $user, $password, $database);

 // create select query
 $sql = "SELECT products.product_name,
 products.unit_price,
 products.unit_in_stock,
 categories.category_name
 FROM products
 INNER JOIN categories
 ON products.category_id = categories.category_id
 ";
  $result = $mysqli->query($sql);
 $result2 = $mysqli->query($sql);
 $Category = $result2->fetch_array();
 ?>



 <h2>Products and its categories </h2>



  

 <table border="1">
  <thead>
  <tr>
  <th>Products </th>
  <th>Unit Price </th>
  <th>Stock Units </th>
  <th>Category </th>
  </tr>
  </thead>
  <tbody>


 <?php

 // Get the query result

 while($rows = $result->fetch_assoc()){?>
       <tr>
      <td><?php echo $rows['product_name']; ?> </td>
      <td><?php echo $rows['unit_price']; ?> </td>
      <td><?php echo $rows['unit_in_stock']; ?> </td>
      <td><?php echo $rows['category_name']; ?> </td>
       </tr>
<?php
 }

 

 




?>

</tbody>

</table>

</body>
</html>

Application Output:



 Download source code:

Comments

Popular posts from this blog

Microsoft Excel top functions.

  Microsoft Excel offers numerous functions to simplify data analysis and calculation. Here are some of the most commonly used and powerful functions: Basic Functions SUM : Adds values. =SUM(A1:A10) AVERAGE : Calculates the mean of numbers. =AVERAGE(A1:A10) IF : Performs logical tests and returns values based on conditions. =IF(A1>10, "Yes", "No") COUNT : Counts numeric values in a range. =COUNT(A1:A10) LEN : Returns the length of a text string. =LEN(A1) Lookup and Reference Functions VLOOKUP : Looks for a value in the first column and returns a value in the same row from another column. =VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup]) HLOOKUP : Similar to Here are practical examples of common Excel functions and how they can be applied in real-life scenarios: 1. SUM Scenario: Calculate the total sales for a week. Example: A B Day Sales Monday 200 Tuesday 150 Wednesday 300 Thursday 250 Friday 100 ...

Creating Wages Sheet using Microsoft Excel

  Creating wages sheet using Microsoft Excel The DAYS360 function in Microsoft Excel calculates the number of days between two dates based on a 360-day year (commonly used in financial calculations). A 360-day year assumes each month has 30 days, simplifying interest and payment schedules. Syntax: DAYS360(start_date, end_date, [method]) Parameters: start_date : The starting date (required). Enter it as a valid date or reference a cell containing a date. end_date : The ending date (required). Enter it similarly to the start_date. method : Logical value (optional). FALSE (default): Uses the U.S. (NASD) method for date calculations. TRUE : Uses the European method. Key Differences Between Methods: U.S. (NASD) : Adjusts the start and end dates depending on whether they fall on the 31st of a month. European : Always treats the start and end dates as the 30th of the month if they are the 31st. Example Usage: Example 1: Calculate days using the U.S. method =DAYS360("01/01/2024", ...

How to use Microsoft Excel PMT function?

  To use the PMT function in Microsoft Excel, follow these steps: Steps to Use the PMT Function: Open Excel : Open your Excel workbook where you want to calculate the payment. Select a Cell : Click on the cell where you want the result (monthly payment). Enter the PMT Function : Use the formula syntax: =PMT(rate, nper, pv, [fv], [type]) Input Arguments : rate : Interest rate per period (e.g., for a monthly rate, divide the annual rate by 12). nper : Total number of payment periods. pv : Present value (loan amount or investment). fv (optional) : Future value, usually 0 for loans. type (optional) : Payment timing: 0 (default): End of the period. 1: Beginning of the period. Press Enter : Excel will calculate and display the periodic payment. Example 1: Monthly Loan Payment Problem: You take a loan of $15,000 with an annual interest rate of 5%, to be repaid over 3 years (36 months). What is the monthly payment? Steps: Select a cell and enter: =PMT(5%/12, 3*12, -...