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

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.

Related

How to use PHP in HTML for mySQL

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.

Make PHP run after form submitted without redirecting to another PHP page to process the data

I'm not sure if this is a duplicate question due to the fact that I'm not even sure how to properly form it (That's why the title of this question makes no real sense). I am beginning to learn PHP so I can utilize SQL databases in my webpages.
My question is, how would I be able to make it so a user types in a password into an input box, which is then used by a PHP script as the password to a MySQL login to display the contents of a table in an HTML table? Now, I have most of this figured out, the only problem is displaying the table on the same page which the password is entered and the submit button is hit. Would I need to use AJAX? Because I don't know the first thing about it. Here is what I have so far:
Index.php:
<DOCTYPE! html>
<html>
<head>
<title>Guy's Random Project</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="scripts.js"></script>
</head>
<body>
<div>
<form action="" method="POST">
<font size="4">Password: </font><input type="text" id="pass" name="pass"/><br>
<input class="buttonGreen" type="submit" value="Submit" id="1" onMouseDown="mouseDown(1)" onMouseOut="mouseUp(1)"/>
</form>
</div>
<table><thead><th>ID</th><th>Name</th><th>Type</th><th>Rating</th></thead><tbody>
<?php include 'getTableData.php'?>
</tbody></table>
</body>
</html>
getTableData.php:
<?php
$servername = "localhost";
$username = "root";
$password = $_POST['pass'];;
$dbname = "testing";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, type, rating FROM crap_food";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"] . "</td><td>" . $row["name"] . "</td><td>" . $row["type"] . "</td><td>" . $row["rating"] . "</td></tr>";
}
} else {
}
$conn->close();
?>
I understand the fact that PHP is run server side, and is only run before any HTML is read by the client, so making a function run when a button is hit wouldn't exactly be possible just using PHP and HTML, but this would be similar to what I'm looking for. I don't want to redirect the user to another page via the form action (Which is why it's blank), I want to keep this all within index.php. Thanks (And sorry for the horrible forming of this question, I'm just a bit confused).
You Use AJAX for this.
$.ajax({
url: 'xxx.php',
data:formData,
cache: false,
contentType:false,
processData:false,
type: 'post',
success: function(response)
{
//do something
}
try this :
$password =$_POST['pass'];
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username,$password);
$sql = 'SELECT firstname FROM users';
$q = $conn->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()):
echo ($r['firstname']);
echo "<tr><td>" . ($r['firstname']) . "</td></tr>";
endwhile;
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" .$pe->getMessage());
}
?>

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

No longer able to connect to mysql using PHP

I keep getting the following error:
Fatal error: Call to a member function fetch_array() on boolean in C:\xampp\htdocs\DeletePlayerSOLN\DeletePlayerExample_SOLN\index.php on line 10
Any idea what the problem is? I searched previous threads and tried to identify the problem for the past few hours. I'm new to PHP.
I'm using Xampp + Mysql.
MySQL connection:
127.0.0.1
3306
root
Default Schema: test
I'm connected through port 443,4433 through Xampp. So I try to connect through /localhost:443/folder..filename..
Connection:
//make a database connection object
$mysqli = new mysqli($server, $user, $pass, $database);
//test if there are database connection errors
if ($mysqli->connect_error)
die("Connect Error " . $mysqli->connect_error);
?>
Index page:
<?php
require "serverCode/connect.php";
$selectPlayer = "SELECT * FROM player ORDER BY playerLastName, playerFirstName";
$results = $mysqli->query($selectPlayer);
$ddlString = "<select name='cboPlayer' size='10'>";
while($row = $results->fetch_array())
{
$ID = $row["playerID"];
$name = $row["playerLastName"] . ", " . $row["playerFirstName"];
$ddlString .= "<option value='$ID'>$name</option>";
}
$ddlString .= "</select>";
$mysqli->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DELETE Player Page</title>
</head>
<body>
<form name="frmPlayer" action="serverCode/deletePlayer.php" method="get">
Select a player:<p><?php echo $ddlString;?>
<input type="submit" name="btnSubmit"></p>
</form>
</body>
</html>
Line 10 is "while($row = $results->fetch_array())"
It is likely that $mysqli->query() is not producing a proper object due to an error. Try replacing
$results = $mysqli->query($selectPlayer);
with
$results = $mysqli->query($selectPlayer) or trigger_error($mysqli->error."[$selectPlayer]");

data retrieved from database in Hebrew presented as question mark

I did all changes as the answer instructed in
this post
in order to be able to print hebrew strings coming from the database but didnt work.
this is my php code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<?php
header('Content-Type: text/html; charset=utf-8');
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "dbName";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
mysql_query("SET NAMES 'utf8'");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Score: " . $row["score"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
every thing works accept that insted of the hebrew strings i only see question marks (???).
any idea why??
Set the Browser's Character Settings to Hebrew.
FireFox:Tools=>Options=>Content=>Advanced=>Fallback Character Encoding = Hebrew
Google Chrome: Menu=>Settings=>Show Advanced Settings=>Language and input settings
UPDATE:
When you save the text first recode the text.
Try using GNU Recode?
$text = mysqli_real_escape_string(recode_string(characterSet,$text));
Where characterSet complies with RFC-1345, e.g. 'latin1'
Valid Character sets: http://www.faqs.org/rfcs/rfc1345.html

Categories