-1

Unfortunately my code isn't working quite well.

The source code:

<!DOCTYPE html>
<html>
<head>
    <title>Query data from News database and display in table</title>
    <meta charset="UTF-8">
    <meta name="description" content="" />
    <meta name="author" content="WRBikAir" />
    <meta name="keywords" content="" />
<style> 
    table, th, td{
        border: 1px solid black;
    }
</style>
</head>

<body>
    <?php
        error_reporting(E_ALL);
        echo "Test 1";
        $con = mysqli_connect("mysql.hostinger.com","u441817146_admin","CBGApp","u441817146_cbg");
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        $sql = "SELECT * FROM News";
        if ($result = mysqli_query($con, $sql)) {
            echo "<table>";
            while($row = $result->fetch_assoc()) {
                $r = json_encode($row);
                echo "<tr><td>" . $r['NID'] . "</td><td>" . $r['headline'] . "</td><td>" . $row['text'] . "</td><td>" . $r['timestamp'] . "</td></tr>";
            }
            echo "</table>";
        } else {
            echo "no result.";
        }
        mysqli_close($con);
        echo "2";
    ?>
</body>
</html>

Everything works fine, except of the output of the NID, headline and timestamp. There are all '{'. Does it mean, that there is now value? because if I simply print them out (encoded of course) there are values e.g.:

{"NID":"1","headline":"Testartikel 2","text":"test test test","timestamp":"15.11.2017, 18:13"}

Does somebody knows a solution?

WR-BikAir
  • 100
  • 11
  • 5
    2 words: "error reporting". – Funk Forty Niner Dec 28 '17 at 19:42
  • 2
    Note: The object-oriented interface to `mysqli` is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface. Before you get too invested in the procedural style it’s worth switching over. Example: `$db = new mysqli(…)` and `$db->prepare("…")` The procedural interface is an artifact from the PHP 4 era when `mysqli` API was introduced and should not be used in new code. – tadman Dec 28 '17 at 19:42
  • 2
    another 2; "mysqli error". – Funk Forty Niner Dec 28 '17 at 19:43
  • 1
    A lot of problems can be detected and resolved by [enabling exceptions in `mysqli`](https://stackoverflow.com/questions/14578243/turning-query-errors-to-exceptions-in-mysqli) so mistakes aren't easily ignored. – tadman Dec 28 '17 at 19:43
  • What is `$resultAray` for? It seems like you are just putting data in that array from your `while()` loop, this is a waste. Why not just display the table row inside the while loop, instead of looping through it a 2nd time? – GrumpyCrouton Dec 28 '17 at 19:43
  • 2
    Popping open a database connection right in the middle of some table code? This sort of programming isn't sustainable, this is already a pretty serious mess of concerns. If you were using a [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) to implement this you'd have patterns you could follow for organizing your code into proper model, view and controller contexts. Frameworks come in many forms from really lean like [Fat-Free Framework](https://fatfreeframework.com/) to exceptionally full-featured like [Laravel](http://laravel.com/) and many spots in between. – tadman Dec 28 '17 at 19:44
  • @GrumpyCrouton Yes it is, I am only testing with that. I will remove this later. ;) – WR-BikAir Dec 28 '17 at 20:02
  • `fetch_object()` returns an object, not an array. – Paul Spiegel Dec 28 '17 at 20:26
  • 1
    w3schools is, sadly, one of the worst possible places to learn PHP. A lot of their coding practices, such as they have them, are extremely out of date and frequently encourage some extraordinarily bad habits. Be careful with a resource like that. Often you'll get quick wins at the expense of a deeper understanding and a better sense of the big picture. Most of programming is not about pounding out code, but of developing a sense of where to put your code, how to structure it, as well as knowing what tools are available so you don't re-invent them by accident. – tadman Dec 28 '17 at 20:46
  • If you take a small amount of time to learn about a framework that you like you'll be significantly more productive. Instead of smashing around with low-level concerns and having to "hand code" everything you can leverage the enormous amount of work the community has done to give you tools. The point of a framework is so you don't spend 80% of your time re-inventing the wheel and 20% on your actual unique application but 100% of your time on your application by using existing tools. – tadman Dec 28 '17 at 20:49
  • And which one do you would recommend? I now got your point, I thought you try to sell me something XD – WR-BikAir Dec 28 '17 at 21:02
  • Well you are running `json_encode` on them which means `$r` is one big json string if you want to ouput those individual fields use `$row['NID']`, `$row['headline']` etc. – prodigitalson Dec 28 '17 at 21:15

2 Answers2

0

You are using $result 2 times on $result = mysqli_query($con, $sql) and in your foreach loop. I changed the one in the foreach loop to $results instead of $result.

Also try turning on error reporting using:

error_reporting(E_ALL);

Try using:

<!DOCTYPE html>
<html>
<head>
<title>Query data from News database and display in table</title>
<meta charset="UTF-8">
<meta name="description" content="" />
<meta name="author" content="WRBikAir" />
<meta name="keywords" content="" />

<style> 
    table, th, td{
        border: 1px solid black;
    }
</style>
</head>

<body>
    <?php
        echo "Test 1";
        $con = mysqli_connect(CENSORED (but working in other classes fine);
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        $sql = "SELECT * FROM News";
        if ($result = mysqli_query($con, $sql)) {
            $resultArray = array();
            $tempArray = array();
            while($row = $result->fetch_object()) {
                $tempArray = $row;
                array_push($resultArray, $tempArray);
            }
            echo "<table>";
            foreach ($resultArray as $results) {
                $r = json_encode($results);
                echo "<tr><td>" . $results['headline'] . "</td><td>" . $results['text'] . "</td></tr>";
            }
            echo "</table>"
        }
        mysqli_close($con);
        echo "2";
    ?>
</body>
</html>
  • But now nothing is displayed. Even not the "Test 1". Only blank. I tried "error_reporting(E_ALL);" but no errors displayed, only a white page. – WR-BikAir Dec 28 '17 at 19:58
  • Did you add your database info? –  Dec 28 '17 at 20:02
  • allright, now I have Test 1 back and an empty table. I updated the code in the question. Can you take a look again? – WR-BikAir Dec 28 '17 at 20:15
0

For everybody who need the working answer.

Thank you to MasterOfCoding, GrumpyCrouton, Paul Spiegel and prodigitalson. Special thanks to tadman for the insider information.

Now the code:

<!DOCTYPE html>
<html>
    <head>
        <title>Query data from News database and display in table</title>
        <meta charset="UTF-8">
        <meta name="description" content="" />
        <meta name="author" content="WRBikAir" />
        <meta name="keywords" content="" />

        <style> 
            table, th, td{
                border: 1px solid black;
            }    
        </style>
    </head>
    <body>
        <?php
            error_reporting(E_ALL);
            echo "Test 1";
            $con = mysqli_connect("...","...","...","...");
            if (mysqli_connect_errno()) {
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
            }

            $sql = "SELECT * FROM News";
            if ($result = mysqli_query($con, $sql)) {
                echo "<table>";
                while($row = $result->fetch_assoc()) {
                    echo "<tr><td>" . $row['NID'] . "</td><td>" . $row['headline'] . "</td><td>" . $row['text'] . "</td><td>" . $row['timestamp'] . "</td></tr>";
                }
                echo "</table>";
            } else {
                echo "no result.";
            }
            mysqli_close($con);
            echo "2";
        ?>
    </body>
</html>
WR-BikAir
  • 100
  • 11