How can I read data from MySQL in different project which is saved by another app?

Issue

I have two separate applications that are working with the same database in MYSQL. The first app in Nodejs and modify data in the database, when I want to read data from the second app coded in PHP, the data looks hidden (no result to select). I can see the data in the database, and I can get the result from the same query that I have in PHP. When I am adding data manually, it is accessible from PHP app.

Code in Node.js

const mysql = require('mysql')

const mysqlconnection = mysql.createConnection({
 host:'172.16.X.X',
 user:'XXX',
 password:'XXXX',
 database:'ramen'
 });

var sql = "INSERT INTO challenge_usersolved (user, challenge_Id, username) 
VALUES (?,?,?)";
var values = [challenge.name , challenge.difficulty, usname];
mysqlconnection.query(sql, values,(err, row)=>{

})

PHP side Code is:

<?php
$db = mysqli_connect('172.16.X.X', 'ramen', 'XXX', 'ramen', '3306');
if (mysqli_connect_errno())
{
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

 $query = "SELECT sum(challenge_Id)*100 as score, username FROM (SELECT 
 Distinct user, challenge_Id, username FROM challenge_usersolved) as T 
 GROUP BY username;";
 $result = mysqli_query($db, $query);
 if (!$result) {
     echo "Could not successfully run query ($sql) from DB: " . 
     mysql_error();
  }

  $rs = mysqli_fetch_assoc($result);
  echo "<html><head><title>Score Board</title></head><body>";
echo "<table align='center' border='1px' style='width:300px; line-height: 30px'>";
echo"<tr><th colspan='2'>Students Score</th></tr><t><th>Username</th> <th>Score</th></t>";
while($rows=mysqli_fetch_assoc($result) ){
    echo "<tr><td>{$rows["username"]}</td><td>{$rows["score"]}</td></tr>";
}


echo "</body></html>";
 ?>

Solution

Your

$rs = mysqli_fetch_assoc($result);

line loads the first record and you do not do anything with it. When your code arrives to the while loop, the next (second) row is attempted to be loaded, but you have a single row as you described in the comment section. The solution seems to be to remove the

$rs = mysqli_fetch_assoc($result);

line.

Answered By – Lajos Arpad

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published