I'm fetching some data from a MySQL database onto a WebPage. I came up with a simple PHP page that queries the database and shows the query in the form of a table and it works just fine.
However, when I try to add bootstrap to the page and style it, the entire page stops working.
Here's my index.php
<!DOCTYPE html>
<html>
<head>
<title>MakersBox</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<center>
<h1>Sensor Testing Dashboard</h1>
<div class="container">
<?php
echo "<table class='table table-hover' align=center>";
echo "<thead><tr><th>Sensor Id</th><th>Temperature</th><th>Light</th><th>Last Updated</th></tr></thead>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "root";
$password = "paanikiboond";
$dbname = "testbox1";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM sensor ORDER BY LastUpdate DESC LIMIT 1");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
</div>
$url1=$_SERVER['REQUEST_URI'];
header("Refresh: 3600 ; URL=$url1");
?>
</body>
</html>
Any idea what I may be doing wrong here?
First, I think you must separte properly your HTML, and your PHP.
In your code, mixte HTML tag + HTML tag from PHP code in your HTML body is... not too regulatory. And very difficult to maintain.
You can, create an architecture like that :
<?php
// Create connexion, and get your results.
$connexion = new PDO();
$results = [];
?>
<!DOCTYPE html>
<html>
<head>
<!-- Your link and scripts-->
</head>
<body>
<h1></h1>
<div>
<?php if (!empty($results){ ?>
<table class='table table-hover'>
<!-- Show your results. -->
<? foreach($results as $result)
{
}
?>
</table>
<?php }else{
echo 'no results found';
}
?>
</div>
</body>
</html>
Also, Boostrap is a Javascript library, It doesn't work directly on PHP, but it read the HTML structure, with your elements and their classes. If your javascript is loaded, and your structure is well done, that work! You have samples and documentation of Boostrtap here;
In your code you forgotten to close your <head></head> element and you've a problem in this lines :
echo "</table>"; // that is PHP, but PHP is not close with `?>`
</div> <!-- That is HTML but in PHP code witouth `echo ''` -->
If PHP and HTML has well separted, you will have fewer problems of forgetting :D You have many links in Internet for understand this good practise
PS : don't forgot to code with proper line indentions: it's much more readable:
<html>
<head> <!-- Very difficult to see we havn't a </head> close tag -->
<body>
<div>
My content
</div>
</body>
</html>
<html>
<head> <!-- Very easy to see we havn't a </head> close tag -->
<body>
<div>
My content
</div>
</body>
</html>
Hope I help you.
for one thing you arent closing your <head>, so your code should be
<!DOCTYPE html>
<html>
<head>
<title>MakersBox</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
...
EDIT: close to the bottom your code should look like
...
echo "</table>";
echo "</div>";
$url1=$_SERVER['REQUEST_URI'];
header("Refresh: 3600 ; URL=$url1");
?>
</body>
</html>
</center><!--that where you forgot to add this as it needs to be closed off-->
</body>
</html>
Also, you might be better off put Javascript on the bottom of the pages, Not sure if it will work.
Second things you need use Web developer tools to diagnosed this issues. it will help a lot. also, you might need to test out different browser if it's same issues or not.
I tried your code. I only find these three mistakes:
You must use echo for build HTML code from PHP and then close your
div container
$conn = null;
echo "</table>";
//wrong way expecting statement
</div>
//correct way for use HTML inside PHP tags
echo "</div>";
The line where you add a header "refresh" generate a warning because
"Cannot modify header information - headers already sent"
$url1=$_SERVER['REQUEST_URI'];
header("Refresh: 3600 ; URL=$url1");
You use <center> tag that it's deprecated so you should use CSS instead and you not close this tag
Related
I'm getting weird results when trying to kind of make a "templating engine". Basically, I want to be able to use PHP variables that contain data from an SQL database.
What happens is that everything works properly with the PHP side, what does not is the page that needs to display this information (index.php).
I'm working on a way to get the website's name from the sql database, so I have something like that on my index:
<?php
include ('php/data/sitename.php');
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $sitename; ?> - Home</title>
<!--Import Google Icon Font-->
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="container">
<!-- HEADER: Navbar -->
<?php $navbar; ?>
<!-- MAIN: Index Page contents -->
<?php $page_index ?>
<!-- FOOTER: Footer -->
<?php $footer; ?>
<?php $sitename; ?>
</div>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
</body>
</html>
This variable comes from a file (that has been included) called sitename.php, with the following code:
<?php
include ('../db.php');
$sql = "SELECT id, sitename FROM GeneralData";
$getname = mysqli_query($conn, $sql);
if ($getname->num_rows > 0) {
while($row = $getname->fetch_assoc()) {
$sitename = $row['sitename'];
echo $sitename;
}
}
?>
Yes, I used echo $sitename;, I know it wont echo the actual data, but I did it to test some things, and here are the results:
Including the file sitename.php to index.php will do nothing, it would be like if it did not exist. However, if I write "echo "123";" on it, it will echo 123 on index. What does not work is what I need.
If I go to sitename.php directly, it will simply output the correct SQL value I requested because I told it to echo (as I stated before). But, it wont work in index, it will simply not work.
Also, I'll leave my project structure here. It might help.
What can I do?
Thanks in advance!
try set GLOBAL for sitename
GLOBAL $sitename;
or
GLOBALS['sitename'];
$sitename = ...
EDIT
try use
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/yourpath/yourfile.php";
include_once($path);
I working on a simple project, and basically what I am doing is that I am creating a simple page from admin panel and then displays it in another page using iframe...
So in the process of displaying the page names, I managed to display all the page names that I have in the database. However, when I try to give them a link so when the user click on them, it redirects them to the specific page. So if there is a page named: new york and he clicks on it, it goes to: /pages/newYork.php ...
The problem: When I give them a link, only 1 page link is given for all the pages. Example: If I had cities named: New York, Bangkok and Amsterdam, the link for all of those pages is only for New york.
Here is my code:
<?php
require_once '../connect.php';
session_start();
if(isset($_SESSION['loggedinAdmin'])){
}else{
header("Location: index.php");
}
// To display content:
$realDisplay = '';
$sql = mysql_query("SELECT * FROM cities");
while($row = mysql_fetch_assoc($sql)){
$displayName = $row['name'];
$realDisplay .= $displayName.'<br/>';
}
echo "<u align='center'>Page names:";
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Display Pages</title>
<style>
a{
text-decoration:none;
font-size:30px;
color:skyblue;
}
</style>
</head>
<body>
<div style="color:red;">
<a href="<?php echo 'pages/'.$displayName.'.php'?>">
<?php echo $realDisplay;?>
</a>
</div>
</body>
</html>
Any thoughts of how to solve this? Also, if there is a better way to do it then it would be great.
Thanks in advance for everybody :)
First, move your loop to the page where you are actually going to display the data.
Second, keep your code clean and readable by putting things where they actually belong. ie. <u align='center'>Page names: doesn't belong where you put it. It goes in the body.
Third, don't forget to properly close your tags. <u align='center'>Page names: has no closing tag.
Finally, don't over-complicate it. You don't need two different vars for the same data row.
<?php
require_once '../connect.php';
session_start();
if(isset($_SESSION['loggedinAdmin'])){
}else{
header("Location: index.php");
}
// To display content:
//$realDisplay = '';
$sql = mysql_query("SELECT * FROM cities");
//while($row = mysql_fetch_assoc($sql)){
//$displayName = $row['name'];
//$realDisplay .= $displayName.'<br/>';
//}
//echo "<u align='center'>Page names:";
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Display Pages</title>
<style>
a{
text-decoration:none;
font-size:30px;
color:skyblue;
}
</style>
</head>
<body>
<div align="center"><u>Page names:</u></div>
<div style="color:red;">
<?php while($row = mysql_fetch_assoc($sql)){
$displayName =$row['name']
?>
<?php echo $displayName;?><br>
<?php } ?>
</div>
</body>
</html>
I have two DIVs which are floating side by side correctly but after embedding the php code as below, the whole page will not show anything. Even When I remove the php code, the page will not show again. The code below is for the div that floats right.
<div style="float:right;">
<?php
echo "<div>
<head>
<link rel='stylesheet' type='text/css' href='chatbox/style/cb_style.css'>
<script type='text/javascript' src='chatbox/ajax.js'></script>
<script type='text/javascript' src='chatbox/chatbox.js'></script>
</head>
<div>";
?>
<div id="container">
<div id="usersOnLine">
<div style="font-weight:bold;margin-top:35%;">Online Users</div>
<div style="height:82%;">
<?php
if (!empty($friends)) {
foreach ($friends as $friend) {
$friend_name = htmlentities($user['username'], ENT_NOQUOTES);
echo "<span>{$friend_name}</span>";
}
}
?>
</div>
<form method="post" action="">
<input type='text' placeholder='search' style='width:145px;'/><a href='#'><span class='glyphicon glyphicon-search'></span></a>
</form>
</div>
<div id="chat_search">
<un>
</div>
</div>
</div>
<div style="clear:both;"></div>
Since you are adding a <head> element into the DOM, you should remove that surrounding div and head and place that first chunk of php code inside your page's <head> section. The browser is getting confused when you introduce a new <head> element that way.
EDIT: to explain further, with a possible example...
You can add those new stylesheet and js entries into your head by appending them to your header include (assuming you are using an include for your main html header - in this example, we call it "header.php", since that's common)
<?php
$addme = '<link rel="stylesheet" type="text/css" href="chatbox/style/cb_style.css">
<script type="text/javascript" src="chatbox/ajax.js"></script>
<script type="text/javascript" src="chatbox/chatbox.js"></script></head>';
ob_start(); // start a buffer
include("header.php");
$contents = ob_get_contents(); // buffer the contents of header.php
ob_end_clean(); // end & clean the buffer
// replace the closing tag with the added stuff
echo str_replace('</head>', $addme, $contents);
?>
So, Im creating a library for other uses, but how can I make content from a file specificly go within the <head> or <body> html tag attribute etc...
for example, this is what im trying to make.
<html>
<head>
<?php include('content/starter/library.php'); ?>
<!-- From that included file, theres a script that put content in the head.-->
</head>
<body>
<!-- From that included file, theres a script that put content in the body -->
</body>
</html>
Im just trying to find another way instead of making multiple files for specific sections and do
<html>
<head>
<?php include('content/starter/library_head.php'); ?>
</head>
<body>
<?php include('content/starter/library_body.php'); ?>
</body>
</html>
Which I don't really want to do. Im not very good with javascript so, There no hope of me trying to figure out how to do this with javascript. Thanks for the answers in the future.
If you want to use one file (as your questions suggests) then one method is to create variables or functions in your library.php file and then echo them in your template
// contents of the library.php file...
<?php
$head_content = "put your <head> content here";
$body_content = "put your <body> content here";
?>
// your HTML file...
<?php include('content/starter/library.php'); ?>
<html>
<head>
<?php echo $head_content ?>
</head>
<body>
<?php echo $body_content ?>
</body>
</html>
UPDATE
To answer the question in your comment, here's an example using a function. You can put all of your code in a function and then just echo that anywhere in your document.
<?php
// contents of library.php...
function head() {
$return = '<link href="file.css" rel="stylesheet">';
$return .= '<link href="another_file.css" rel="stylesheet">';
return $return;
}
// your HTML file...
<html>
<head>
<?php echo head(); ?>
</head>
PHP functions explained: http://www.w3schools.com/php/php_functions.asp
What I would like to know is when I grab data from a Database how can I format it with PHP so it looks nice. All i seem to be getting is a Blank white page and when i inspect the page with google chromes inspect element it says that i've got a 500 internal error.
For example, I'm using PDO to connect to the database. Heres my code:
<?php
$hostname='localhost';
$username='root';
$password='root';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=fitness", $username, $password);
$sql = "SELECT * FROM fitness";
$fitnessResult = $dbh->query($s ql);
$fitness = $dbh->fetchObject($fitnessResult);
foreach ($fitness AS $fit) {
$fitnessArray[] = ['name' => $fit->name, 'id' => $fit->description];
}
$dbh = null;
}
catch (PDOexception $e) {
echo "Error is: " . $e-> etmessage();
}
and here is my html im using the twitter bootstrap framework.
<?php
include'inc/connect.inc.php';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fitness</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap- theme.min.css">
<link rel="stylesheet" href="css/style.css" />
<!-- Latest compiled and minified JavaScript -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-4">
<?php foreach ($fitnessArray AS $fitness) { echo '<h2>'. $fitness['name'] .'</h2>'; echo '<p>' . $fitness['description'] . '</p>';} ?>
</div>
<div class="col-xs-8">
<p>Dummy Text</p>
</div>
</div>
</div>
</body>
</html>
So how would I put the name into a H1 tag and the description into P tag.
Thanks
You might want to try something like the following which keeps the objects and fetchs all in an arrary
$fitnessResult = $dbh->query($sql);
$fitnessArray = $fitnessResult->fetchAll(PDO::FETCH_OBJ);
then in your html
<?php foreach ($fitnessArray AS $fitness): ?>
<h2><?=$fitness->name ?></h2>
<p><?=$fitness->description ?></p>
<?php endforeach; ?>
see official docs for fetchAll()