How to use PHP in HTML for mySQL - php

I am trying to use php for the first time to connect to MySQL on the raspberry pi. Both the server and MySQL are running on the Pi and I want to tweak my index.html file to show some value that is in the data base. Normally for I would be able to do just that with pyton but I have no clue if I can do that with php. Here is my index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ziks</title>
<link href="CSS/style1.css" rel="stylesheet" type="text/css">
<style type="text/css">
body {
background-color: #FFFFFF;
background-image: url(Images/twe_background-1920x1080.jpg);
}
</style>
</head>
<body>
<div class="header">
<p><strong>Welcome to Ziks</strong></p>
</div>
<p> </p>
<div class="box">
<p> Wishing every one a happy life! </p>
<form method="GET" action="ftp://47.55.90.215:21">
<input type="submit" value="Click here to view Disk">
</form>
<body>
<html>
<body>
</body>
</html>
</body>
<div class="image"></div>
<iframe src="http://free.timeanddate.com/clock/i5nb4b3g/n1127/szw160/szh160/hoc9b8578/hbw10/hfc754c29/cf100/hnc432f30/hcw2/fav0/fiv0/mqcfff/mqs4/mql25/mqw12/mqd78/mhcfff/mhs2/mhl5/mhw2/mhd78/hhcfff/hhs2/hhl50/hhw8/hmcfff/hms2/hml70/hmw8/hmr4/hscfff/hss3/hsl70/hsw3" frameborder="0" width="160" height="160"></iframe>
<video width="400" controls>
<!--<source src="///smb://zikpc/f/test.mp4" type="video/mp4">-->
<!--<source src="///smb://zikpc/f/test.ogg" type="video/ogg">-->
<source src="1.mp4" type="video/mp4">
<source src="1.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
</div>
</body>
</html>
This index.html file works fine. All I want to do is write some php in it to connect to MySQL. The current method I'm using in python is:
# External module imports
import time
import os
import datetime
import MySQLdb
os.system('sudo modprobe w1-gpio')
os.system('sudo modprobe w1-therm')
# Connect to mysql
db=MySQLdb.connect("localhost","zikmir","gforce","temp_database")
cursor=db.cursor()
while True:
# Initialization
sensor= "/sys/bus/w1/devices/28-011620ee98ee/w1_slave"
# Open the file for sensor
file = open(sensor)
# Read all of the text in the file.
text = file.read()
# Close the file now that the text has been read.
file.close()
# Split the text with new lines (\n) and select the second line.
second_line = text.split("\n")[1]
# Split the line into words, referring to the spaces, and select the 10th word (counting from 0).
temp_data = second_line.split(" ")[9]
# The first two characters are "t=", so get rid of those and convert the temperature from a string to a number.
temp = float(temp_data[2:])
# Put the decimal point in the right place and display it.
temp = temp / 1000
# Display time
t= datetime.datetime.now()
print t,temp
# Push data into mySQL
sql = "INSERT INTO time_temp VALUES(now(),%s)"
cursor.execute (sql,(temp,))
db.commit()
# Wait 5 seconds
time.sleep(5)
My question is how would I be able to do this in php within the index.html file? Any help would be appreciated!
This is my website

MySQLi Object-Oriented
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
PDO
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

You have a number of choices. The simplest, IMHO, would be something like the following.
Rename your index.html file to index.php (make sure that your web server looks for index.php as well as index.html and index.htm).
Your index.php would then be modified to look something like this:
<?php
//Open MySQL connection
//Get the data you want into a string variable called $info
print <<< END
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ziks</title>
<link href="CSS/style1.css" rel="stylesheet" type="text/css">
<style type="text/css">
body {
background-color: #FFFFFF;
background-image: url(Images/twe_background-1920x1080.jpg);
}
</style>
</head>
<body>
... (rest of HTML excluded for brevity)
END;
?>
Simply put the $info variable where ever you want the data to appear in the HTML data.
The construct:
print <<< END
<<<what you want to print>>>
END;
is called a "heredoc" and is very handy.
I have not described how to actually get the data from the database since your question seemed more about the process of using PHP to output HTML with data from a database. Look at the PDO documentation (PDO documentation) to quickly get up to speed on DB access in PHP.

Related

SQLSTATE[HY000] [2002] Connection refused (right port)

I would like to print the measured data of my weatherstation on a website. Therefore I would like to connect my MariaDB-database. Here ist my code.
<?php
$username = "root";
$password = "M1lVhPuio";
$database = "weatherbot";
try {
$pdo = new PDO("mysql:host=raspberrypi;port=3306;database=$database", $username, $password);
//Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
die("ERROR: Could not connect. ". $e->getMessage());
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Wetterstation </title>
</head>
<body>
<h1> Meine Wetterdaten </h1>
</body>
</html>
When I open the website, I see this: "ERROR: Could not connect. SQLSTATE[HY000] [2002] Connection refused"
There's already an entry in this forum about this case, but adding the port didn't work for me. (3306 is the right port.)
Like Sergio Rinaudo said, I had to use the default address instead of "raspberrypi":
$servername = "127.0.0.1";
try {
$pdo = new PDO("mysql:host=$servername;port=3306;database=database", root, M1lVhPuio);
Thank you for your help!

How to connect MySQL server without putting user/pass in the main page [duplicate]

This question already has answers here:
How to secure database passwords in PHP?
(17 answers)
Closed 2 years ago.
I have a main page on my site and I am trying to make a connection to the MySQL server and get some data from the database.
But the problem is that when I want to establish a connection I have to put the username and password in the page which doesn't seem wise to me.
I added a part of my code related to this problem.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";
$connection = new mysqli($host , $userName , $password , $dbName);
if ($connection->connect_error) {
die("Connection failed due to this error : " . $connection->connect_error . '<br>');
}
else{
echo "Connected successfully";
{
</body>
</html>
Put your connection code into another file, like connection.php and in every page you want to connect you should require_once "connection.php", also you could use variables from that file if you connect it, also instead of require_once you can use just require, but look at the internet differences between them
Normal practice is to put the mysql data in a separate php file. For example:
dbmain.php
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";
$connection = new mysqli($host , $userName , $password , $dbName);
?>
then you can include this file in all php files which require db connection.
<?php include_once("dbmain.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
/// php commands, such as
//if ($result = $mysqli -> query("SELECT * FROM dbtable1")) {
// echo "Returned rows are: " . $result -> num_rows;
// Free result set
// $result -> free_result();
//}
//$mysqli -> close();
?>
</body>
</html>

Show Output/Echo of PHP File executing at load on webpage

im trying to create my first website and Im clueless in this case.
So I have a MySQL-Database with a table. And I have a php-File called database.php which reads from the database and echos all the lines of a query:
<?php
$servername = "xxxxxxxxxx.hosting-data.io";
$username = "xxxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ID, Name, Beschreibung, Datum, Uhrzeit FROM Termine";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["ID"]. " - Name: " . $row["Name"]. " - Beschreibung: " . $row["Beschreibung"]. " - Datum: " . $row["Datum"]. " - Uhrzeit: " . $row["Uhrzeit"]."<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Now on my index.php I want to execute this php-code on calling/loading the webpage and print all the lines (data entries).
But i have no idea how to get the echo (=data entries) of the php file printed in the body of my webpage. I read about AJAX and using a js-script but I still wasnt able to figure it out.
Thanks for your help.
Option 1: Place your PHP code inside the HTML body.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo 'Hello World';
// ...
?>
</body>
</html>
Option 2: Create a separate PHP file containing your code above and include/require it into your body.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
include_once('your_php_file.php');
?>
</body>
</html>
Option 3: Call your PHP file using an AJAX call (e.g. by using jQuery load()).
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="aDiv"></div>
<script> $( "#aDiv" ).load('your_php_file.php', function() { console.log('Loaded'); });</script>
</body>
</html>
If your index file is index.php then the PHP code will be run when you load the webpage. That is assuming, of course, that your web server (local or remote) has PHP installed.

How to build simple page with data from MySQL table?

I spent few days, but since I am completely new in JSON or PHP programming, can't solve my problem without your help.
Here is my problem - I have MySQL DB, I need to extract data from the table and build simple (for e.g. 2 columns) page (html or whatever) with table which consist info from my DB.
I wrote php connector, here it is:
<?php
//require_once("data_connector.php"); //!connector
$dbtype = "MySQL";
$username = ''; // USERNAME
$password = ''; // PASSWORD
$hostname = ''; // HOSTNAME
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("MASTER_TRACKER_DB",$dbhandle)
or die("Could not select MASTER_TRACKER_DB");
/*
//execute the SQL query and return records
$result = mysql_query("SELECT SITE_ID, 3G_SITE_ID FROM MASTER_TRACKER WHERE SITE_ID LIKE '%ABK000%'");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "SITE_ID:".$row{'SITE_ID'}." 3G_SITE_ID:".$row{'3G_SITE_ID'}.
"<br>";
}
*/
$data = new JSONDataConnector($dbhandle, $dbtype);
//$data->render_table("MASTER_TRACKER_DB.MASTER_TRACKER","SITE_ID","SITE_ID, 3G_SITE_ID");
$data->render_sql("SELECT SITE_ID, 3G_SITE_ID FROM MASTER_TRACKER_DB.MASTER_TRACKER WHERE SITE_ID LIKE '%ABK000%'", "", "SITE_ID, 3G_SITE_ID");
$data->dynamic_loading(30);
//close the connection
//mysql_close($dbhandle);
?>
From this script I see that I am able to connect to DB (I am getting Connected to MySQL message).
Also, if I comment out PHP part which build table, I see that it can build table.
So, as next step, I would like to build table using JSON, so I will use it with Webix, so I made this page:
<!DOCTYPE html>
<html>
<head>
<title>Loading from DB</title>
<link rel="stylesheet" href="codebase/webix.css" type="text/css">
<script src="codebase/webix.js" type="text/javascript"></script>
</head>
<body>
<div class='header_comment'>Loading from DB (sqllite + php)</div>
<div id="testA" style='height:600px'></div>
<hr>
<script type="text/javascript" charset="utf-8">
webix.ready(function(){
grida = webix.ui({
container:"testA",
view:"datatable",
columns:[
{ id:"SITE_ID", header:"SIZE_ID", width:200 },
{ id:"3G_SITE_ID",header:"3G_SITE_ID", width:120 }
// { id:"size", header:"Size" , width:80 },
// { id:"architecture", header:"PC", width:60 }
],
autowidth:true,
url: "data/data.php"
});
});
</script>
</body>
</html>
But seems that I missed something since it shows empty table,
Can anyone please help me to make this page working?
Thanks to all in advance,
Roman

Enabling both a PHP parser and an Include statement

I have an existing SHTML page with a few INCLUDE statements for menu's. This has worked well. To this point, my .htaccess file has looked like:
Options +FollowSymLinks
And my Include statement looked like this:
<!--#include virtual="menu_primary.shtml" -->
I have a new need to add some PHP code to the main page. The PHP code queries a Mysql database to return a single row. If the row exists in the database, I want to show it on the SHTML page. If the row does not exist, do nothing. Here's the PHP code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT notice from notification where page = 'home'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Message is: " . $row["notice"]. "<br>";
}
} else {
echo "";
}
mysqli_close($conn);
?>
</body>
</html>
When I implemented this PHP code, the page seemed to interpret everything after the Greater Than symbol as text. When I posted that problem, someone on this forum suggested altering the .htaccess file to include a PHP parser. For a while. I altered my .htaccess file to look like this:
Options +FollowSymLinks
<FilesMatch "\.(htm|html|shtm|shtml)$">
SetHandler application/x-httpd-php5
</FilesMatch>
However when I do that, the PHP code works fine and I display the data from the database on the SHTML page, but the #Include statements no longer work. How can I enable both the PHP and #Include code together in the same SHTML page? Thanks very much for looking at this.
In your PHP script you can invoke the virtual function to work with your SSI
<?php
virtual('menu_primary.shtml');
There's a very old page that talks about this in more detail
http://www.zytrax.com/tech/php/php_ssi.htm

Categories