Home > database >  can't receive info from my mySQL database, despite having seen a tutorial doing exactly the sam
can't receive info from my mySQL database, despite having seen a tutorial doing exactly the sam

Time:05-20

So i am trying to make a program that reads and writes to a MySQL database, which led me to a youtube tutorial. My problem is that despite going through exactly the same process as the fellow in the tutorial, i end up with an empty server despite what should be popping up. My Code is as follows, which should grab every entry in the applicant_info table in my applicants database, and display it on the localhost:3000 browser. Instead, it displays nothing, which im guessing is because it is unable to fetch the information, but i have no idea why that's the case as again, i have followed a tutorial down to the letter.

const express = require("express");
const mysql = require('mysql');

const connection = mysql.createConnection({
        host    : 'localhost',
        user    : 'root',
        password: 'password',
        database: 'applicants'
});

const app = express();

app.get('/', (req, res) => {
    let sql = "SELECT * FROM applicant_info";
    connection.query(sql, (err, results) =>{
        res.send(results);
    })
});

app.listen('3000', () => {
    console.log('Server running on port 3000');
    connection.connect((err) => {
        if(err) {
        };
        console.log('Database Connected!');
    })
});

a sidenote about the code is that i for some reason can't run it with the "throw" command, which is why the 'err' if-statements are currently empty. I hope to dear god that this is not the cause, as i have no idea how to fix it.

Here is a picture of what i receive from my browser: Image Description

CodePudding user response:

You have an issue with your require :

Error: Cannot find module 'mySQL'

it should be :

const mysql = require('mysql');

so your server does not run, and you have a 404 on the browser.

Once it's fixed, start your server,
and you should see this in the console :

Server running on port 3000
Database Connected!

you should see your data when going to http://localhost:3000

edit:

added more debug to your code :

app.get('/', (req, res) => {
    console.log('get called');
    let sql = "SELECT * FROM users";
    connection.query(sql, (err, results) =>{
        res.send(results);
    })
});

app.listen('3000', () => {
    connection.connect((err) => {
        if(err) {
          console.log('Database not connected!');
        } else {
          console.log('Server running on port 3000');
          console.log('Database Connected!');
        }
    })
});

CodePudding user response:

$servername = "localhost";
$username = "username";
$password = "password";$conn = new mysqli($servername, $username, $password);//Check connection if ($conn->connect_error) { die("Connection failed: ". $conn->connect_error);}echo "Connected successfully"; check DB is connected or not
  • Related