Is there any way I can display MySQL data using Node.JS onto a .blade.php or .php file?

Updated: Feb 19, 2025

Is there any way I can display MySQL data using Node.JS onto a .blade.php or .php file?

Yes, you can display MySQL data using Node.js and render it in a Blade.php or PHP file. Here's a step-by-step guide on how to achieve this:

  1. Set up your Node.js project: First, create a new Node.js project using npm init or your preferred package manager. Install the necessary dependencies: express, mysql, and ejs (for Blade.php, you'll need to install ejs-mate instead of ejs).
npm install express mysql ejs-mate
  1. Create a new file called app.js and set up the basic Express server:
const express = require('express');
const mysql = require('mysql');
const path = require('path');
const ejs = require('ejs-mate');

const app = express();
const port = process.env.PORT || 3000;

app.engine('html', ejs.renderFile);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));

app.get('/', (req, res) => {
  res.render('index');
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
  1. Set up the MySQL connection:
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'your_username',
  password: 'your_password',
  database: 'your_database'
});

connection.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL database');
});
  1. Create a new route and controller to fetch data from the MySQL database and render it in a Blade.php or PHP file:
app.get('/data', (req, res) => {
  connection.query('SELECT * FROM your_table', (err, results) => {
    if (err) throw err;
    res.render('data', { data: results });
  });
});
  1. Create a new Blade.php or PHP file called data.blade.php or data.php in the views folder:
@extends('layouts.app')

@section('content')
  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      @foreach ($data as $item)
        <tr>
          <td>{{ $item.id }}</td>
          <td>{{ $item.name }}</td>
          <td>{{ $item.email }}</td>
        </tr>
      @endforeach
    </tbody>
  </table>
@endsection

or

<?php
$data = $data;
?>

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($data as $item): ?>
      <tr>
        <td><?php echo $item['id']; ?></td>
        <td><?php echo $item['name']; ?></td>
        <td><?php echo $item['email']; ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>
  1. Update the app.js file to include the new route:
app.get('/data', (req, res) => {
  connection.query('SELECT * FROM your_table', (err, results) => {
    if (err) throw err;
    res.render('data', { data: results });
  });
});

Now, when you visit the /data route, the data from your MySQL database will be fetched and displayed in the Blade.php or PHP file.