Inserting mySQL into a div?

Hi there,

I’m handcoding a personal blog in my spare time, but I’ve run across a problem. I’m trying to get the div to display the title selected from the database, but instead it just removes the div altogether (as well as the divs lower down in the code). Here’s the segment of code:

<!DOCTYPE html>
<?php
include("dbconfig.php");
?>
<html lang="EN-US">
<head>

<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->



<title>Eyes on the Ball</title>
<meta name="description" content="An online sportsblog covering a wide variety of sports.">
<meta name="keywords" content="Blog, Sportsblog, Sports, Football, NFL, Cricket, Boxing, Tennis,   Other Sports, Soccer">
<meta charset="UTF-8">


<link rel="stylesheet" type="text/css" href="Styles.css"> 
<style>


#mainarticle {
    background-color:orange;
    width: 50%;
     height: 500px;
    margin: 25px;
    border-style: solid;
    position: absolute;
    border-width: 3px;
    top: 112px;
}



 <?php
$statement = $mysqli->query('SELECT ID, Title FROM posts ORDER BY ID DESC');
	 while($row = $statement->fetch()){
				
	     echo '<div id="mainarticle">';
		  echo '<h1><a href="viewpost.php?id='.$row['ID'].'">'.$row['Title'].'</a> </h1>';
			echo '</div>';
		}
		
?>

Hi jupjamie welcome to the forum

You’re writing div, h1, a inside the head’s style tag?

1 Like

Thank you very much :smile:
I’m sorry, I don’t quite understand your question. Could you possibly explain it to me?

The </head><body> tags should appear part way through the code you posted but they don’t.

1 Like

Ah, sorry, I only posted a snippet of the code. Here’s the full thing:

<!DOCTYPE html>
<?php
include("dbconfig.php");
?>
<html lang="EN-US">
<head>

<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

<title>Eyes on the Ball</title>
<meta name="description" content="An online sportsblog covering a wide variety of sports.">
<meta name="keywords" content="Blog, Sportsblog, Sports, Football, NFL, Cricket, Boxing, Tennis, Other Sports, Soccer">
<meta charset="UTF-8">

<link rel="stylesheet" type="text/css" href="Styles.css"> 
<style>


 #mainarticle {
     background-color:orange;
        width: 50%;
    height: 500px;
    margin: 25px;
    border-style: solid;
        position: absolute;
        border-width: 3px;
    top: 112px;
}

 #secondarticle {
     background-color:orange;
        width: 300px;
    height: 250px;
    margin: 25px;
    border-style: solid;
       border-width: 3px;
    position: absolute;
    right: 381px;
    top: 112px;

}

 #thirdarticle {
    background-color:orange;
        width: 300px;
    height: 250px;
    margin: 25px;
    border-style: solid;
        border-width: 3px;
    position: absolute;
    right: 78px;
    top: 112px;
 
 }

 #fourtharticle {
    background-color:orange;
        width: 300px;
    height: 250px;
    margin: 25px;
    border-style: solid;
        border-width: 3px;
    position: absolute;
    right: 381px;
    top: 362px;

 }

 #fiftharticle {
    background-color:orange;
        width: 300px;
    height: 250px;
     margin: 25px;
    border-style: solid;
        border-width: 3px;
    position: absolute;
right: 78px;
top: 362px;
  }

#othernflarticles {
    width: 150px;
    padding: 10px;
    background-color: #81DAF5;
    margin: 0px;
    font-family:Verdana, Arial, Helvetica, Geneva, sans-serif;
    position: absolute;
    left: 2.5%;
    top: 100%;	 
}

 #otherfootballarticles {
    width: 181px;
    padding: 10px;
    background-color: #81DAF5;
    margin: 0px;
    font-family:Verdana, Arial, Helvetica, Geneva, sans-serif;
    position: absolute;
    left: 25.5%;
    top: 100%;	 
}

#othersportsarticles {
    width: 173px;
    padding: 10px;
     background-color: #81DAF5;
    margin: 0px;
    font-family:Verdana, Arial, Helvetica, Geneva, sans-serif;
     position: absolute;
    left: 50.5%;
    top: 100%;	 
}    

 #mostpopulararticles {
    width: 177px;
    padding: 10px;
    background-color: #81DAF5;
    margin: 0px;
    font-family:Verdana, Arial, Helvetica, Geneva, sans-serif;
    position: absolute;
    left: 75.5%;
     top: 100%;	 
 }
</style>
</head>
<body>
<header>
<img src="Eyes on the Ball logo.jpg" alt="Eyes on the Ball logo" border ="5" style="position:fixed; z-index: 1; width:170;height:100px;">
</header>

 <nav>




 <a href="#"" class="home_button">Home</a> 
 <a href="#"" class="nfl_button">NFL</a>  
<a href="#"" class="football_button">Football</a> 
<a href="#"" class="other_sports_button">Other Sports</a> 
<a href="#"" class="about_us_button">About us</a> 


<form class="search">
    <input type="text" placeholder="Search..." required>
    <input type="button" value="Search">
</form>

<?php
 $statement = $mysqli->query('SELECT ID, Title FROM posts ORDER BY ID DESC');
	 while($row = $statement->fetch()){
				
	        echo '<div id="mainarticle">';
			  echo '<h1><a href="viewpost.php?id='.$row['ID'].'">'.$row['Title'].'</a></h1>';
				 echo '</div>';
		    }
		
?>


 <div id="secondarticle"> hi </div>
 <div id="thirdarticle"> hi </div>
 <div id="fourtharticle"> hi </div>
 <div id="fiftharticle"> hi </div>

 <div id="othernflarticles"> Other NFL articles </div>
 <div id="otherfootballarticles"> Other Football articles </div>
<div id="othersportsarticles"> Other Sports articles </div>
<div id="mostpopulararticles"> Most popular articles </div>

</body>
</html>

If you look at the page in the browser’s view-source, the closing form tag is the last of the HTML ?

It sounds like the db stuff is breaking and causing the script to exit.

Try temporarily changing the beginning of the file like so.

<!DOCTYPE html>
<?php
error_reporting(E_ALL); // DEBUGGING ONLY
ini_set('display_errors', 'true'); // DEBUGGING ONLY

include("dbconfig.php");
?>
<html lang="EN-US">
<head>
1 Like

Ooooh, I didn’t realise that viewing the page source could come up with an error! Here’s what it says:

Fatal error: Call to undefined method mysqli_result::fetch() in /home/eyesonth/public_html/index.php on line 157

Line 157 for me is the blank line between the fetch and the echo call, as you can see here: https://gyazo.com/40b3bcb6d0f49b4e74ea97048c341feb

Does this mean that I haven’t used fetch right? I’m still a bit confused :x

It sounds like the query isn’t returning what you want it to
http://php.net/manual/en/mysqli.query.php

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

Try

<?php
 $statement = $mysqli->query('SELECT ID, Title FROM posts ORDER BY ID DESC');
 var_dump($statement); // DEBUGGING ONLY
 exit; // DEBUGGING ONLY
	 while($row = $statement->fetch()){
1 Like

The page source now has this:

object(mysqli_result)#2 (5) {
[“current_field”]=>
int(0)
[“field_count”]=>
int(2)
[“lengths”]=>
NULL
[“num_rows”]=>
int(4)
[“type”]=>
int(0)
}

I don’t understand if this is good or bad. What are the numbers next to int?

“int” is the datatype of the value associated with the array key.

http://php.net/manual/en/class.mysqli-result.php

“current_field” is where the “pointer” is. (I would ignore that for now)
“field_count” is 2 i.e. “ID” and “Title”
“lengths” is NULL - not good.
http://php.net/manual/en/mysqli-result.lengths.php

The mysqli_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set.

“num_rows” is 4 - are there only 4 rows in the posts table?
“type”, AFAIK, is if the result is numeric, associative, or both

Because of the NULL I’m guessing (but could very well be wrong) the 4 “rows” are

0 => NULL
ID => NULL
1 => NULL
Title => NULL

Are you sure the posts table has “ID” and “Table” columns - both spelling and case.

Also, MySQL has “reserved words” that have meaning to MySQL
https://dev.mysql.com/doc/refman/5.5/en/keywords.html

IMHO it’s best to avoid using them as column names. eg.
post_id and post_title would be a wiser choice of names.

But if you must, they should be enclosed in the query. Which is a good habit to get into anyway IMHO eg.

$statement = $mysqli->query("SELECT 'ID', 'Title' FROM posts ORDER BY ID DESC");
1 Like

If a row means an entry, then yes there are four currently (which would mean there are five columns - ID, Title, Body, Category and Author.) These rows are made up of one proper article with a Title, Body, Category and Author all in the right place, and then three other entries with random letters in each one, but still having Title, Body and Category filled out.

The posts table definitely has “ID” and “Title” both spelt correctly, and both in the correct case.

Thank you for the heads up about reserved names - I’ll keep them as they are for this project just so I don’t confuse myself, but I’ll make sure to not use any reserved words in the future. I’ve enclosed them in the query for now, but I’m still getting the same error message/vardump result.

Has something changed in HTML5 that allows you to have multiple DIVs all with the same ID? I know it won’t make any difference to the problem you’re having, but I thought DIV IDs had to be unique, to use the same styling for multiple ones would use a class instead. Also (again, this may be a thing in HTML5 I haven’t got familiar with yet) are the quotes correct in these links in the nav section?

 <a href="#"" class="home_button">Home</a> 
 <a href="#"" class="nfl_button">NFL</a>  
<a href="#"" class="football_button">Football</a> 
<a href="#"" class="other_sports_button">Other Sports</a> 
<a href="#"" class="about_us_button">About us</a> 

I’m thinking of how there are two after the link placeholders.

If you’re still getting the same error, have you checked whether your code to connect to the database (presumably in “dbconfig.php”) is working properly?

I suspect the issue with it reporting an error on line 157 which appears to be blank is that PHP refers to the first line as zero and your editor refers to it as one, or the other way around.

1 Like

Any id must be unique on a page. And yes, there are too many quotes. The code should be

<a href="#" class="home_button">Home</a> 
<a href="#" class="nfl_button">NFL</a>  
<a href="#" class="football_button">Football</a> 
<a href="#" class="other_sports_button">Other Sports</a> 
<a href="#" class="about_us_button">About us</a>

Running your code through the W3C validator might find other “funnies”.

1 Like

Thank you guys, I’ve fixed the problem with there being too many quotes. You mentioned that IDs had to be unique, but I can’t seem to spot where I’ve used one twice?

The code to connect to the database is definitely working, I’ve included it in other pages and it runs just fine.

My editor does indeed refer to the first line as one, which would then suggest that the error is actually on line 156, which is to do with the fetch call. Have I not used it right? It’s my first time ever trying it out, and I can’t see where I’ve gone wrong with it.

You have this section of code:

while ($row = $statement->fetch()) {
  echo 'div id="mainarticle">';
  ... some other stuff
  }

So it will create a div with that id for each row that comes back from your query.

1 Like

Ah, that will create a new div? In that case, how would I go about assigning that to the div with that name already in place?

You could open the div before the loop, and close it after the loop

1 Like

As someone mentioned above, the error in the fetch() suggests that the query hasn’t worked for some reason. So it isn’t necessarily that you’re using it incorrectly, but you should really check that the query has worked before using the result. All that would do in this case is allow you to handle the problem, though.

Does the query work in phpmyadmin or whatever equivalent you use?

1 Like

I use PHPmyadmin, where can I try to run the query?

I don’t use mysqli myself, but a quick read of the doc suggests that fetch() is to be used to get data from a prepared statement. If you change the code to use fetch_assoc() instead, does it work any better?

 while($row = $statement->fetch_assoc()){
1 Like