-2

I would be grateful for any insight relating to my issue described below. Please excuse my ignorance as I am working to lessen it.

I am using PHPMyAdmin to create the database and php to connect a website to the database. I have confirmed that the database does connect and I can create a form on the website to populate fields in the database.

What I cannot do is create a Query that returns results and publishes them on the website. I have used YouTube videos, Code Igniter tutorials and W3 tutorials and continually end up with the same problem. Deduction leads me to believe that there are issues with my database.

This is the relevant code:

 <?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "news";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, title, slug FROM ci_nws";
$result = mysqli_query($conn, $sql);


if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "<br> id: ".$row["id"]. " - Name: ".$row["title"]. " " .$row["slug"] . "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>

The error message refers to line 18

if (mysqli_num_rows($result) > 0) {

the "0 results" does display below the error message.

I am using

Database server Server: Localhost via UNIX socket Server type: MySQL Server connection: SSL is not being used Documentation Server version: 5.6.46-cll-lve - MySQL Community Server (GPL) Protocol version: 10

Server charset: UTF-8 Unicode (utf8)

Web server cpsrvd 11.78.0.38 Database client version: libmysql - 5.1.73 PHP extension: mysqliDocumentation curlDocumentation mbstringDocumentation PHP version: 7.2.7

phpMyAdmin Version information: 4.8.3

If relevant I am using Godaddy economy hosting package.

Any thoughts? Thanks in advance.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141

1 Answers1

2

You missed the database name from the connection

<?php
$servername = "localhost";
$username = "";     //<-- needs a valid username
$password = "";     //<-- needs a valid passsword for this username
$dbname = "news";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//             -----------------missing part here     ^^^^^^^

Remember, A MySQL instance can have multiple databases within it. So you must select the database you want to use either as part of the connection call or as a seperate mysqli_select_db() call

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149