Getting a csv file from mysql over PHP for dygraph.js - php

My Goal is to create a Website which displays data from my mysql database with dygraph.js. The website should load the data every time it is opened because my Mysql database receive new data every hour.
My Problem is that I dont know how I can make a PHP site that returns a csv file (not download it).
Basicly my Question is: Is it possible to connect mysql and dygraph? if yes, how?

Okay I got a solution.
For everyone who has the same problem:
I found a really nice tutorial from glaskugelsehen: https://glaskugelsehen.wordpress.com/2014/05/24/tutorial-speicherung-von-arduino-messdaten-auf-webserver-und-deren-darstellung-teil-5/
Its german but you can use the code without understanding the language
Because the tutorial is really old I had to translate it into mysqli and do some little changes. Then I ended up with this php code:
<html>
<head>
<br>
<script type="text/javascript"src="libraries/dygraph.min.js"></script>
<link rel="stylesheet" src="CSS/dygraph.css" />
</head>
<body style="color: rgb(0, 0, 0); background-color: rgb(77, 77, 77)" alink="#ee0000" link="#0000ee" vlink="#551a8b">
<div style="text-align: center;"><span style="color: rgb(255, 255, 255);">Daten aus MySQL<br></span>
<table style="margin:0px auto" border="0" width="500" align="center">
<tr>
<td style="background-color: #FFFFFF">
<div id="graphdiv2"
style="width:500px; height:300px;"></div>
<script type="text/javascript">
g2 = new Dygraph(document.getElementById("graphdiv2"),
<?php
$mysql_host = "****";
$mysql_db = "****";
$mysql_user = "****";
$mysql_pw = "****";
$connection = new mysqli($mysql_host, $mysql_user, $mysql_pw, $mysql_db); // Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$abfrage = "SELECT DATE_FORMAT(Zeit, '%Y/%m/%d %H:%i:%s') AS date, Temperatur, Luftfeuchtigkeit FROM messung";
$ergebnis = mysqli_query($connection,$abfrage);
echo "["; // start of the 2 dimensional array
while($row = mysqli_fetch_array($ergebnis))
{
$utime = strtotime($row[datum]);
$diffutime = $utime - $lastutime;
if ($diffutime > 600) {
echo "["."new Date(\"".$row[date]."\")".",NaN,NaN],";
}
else {
echo "["."new Date(\"".$row[date]."\")".",".$row[Temperatur].",".$row[Luftfeuchtigkeit]."],";
}
$lastutime = strtotime($row[datum]);
}
echo "]";
mysqli_close($connection);
?> ,
{ rightGap: 20,
connectSeparatedPoints: true,
labels: [ "Zeit", "Temperatur", "Luftfeuchtigkeit" ] } // options
);
</script>
</td>
</tr>
</table>
</div>
</body>
</html>
If somebody wants to use this code he has to fill in his mysql information.
Hopefully this is helpful

Related

Unable to Retrieve data from the postgress database using Php?

I have created a Php file, which fetches the data from the Postgres Database, but when I run the file it doesn't displays the contents (records) which are present in the database table.
I ran this using both Apache server and Python SimpleHTTPServer also.
I restarted the Postgres server too.
Below is the code of that file:
index.php
<!DOCTYPE html>
<html>
<head>
<title>
webpage
</title>
</head>
<body>
<h1>
INFORMATION OF DATABASE
</h1>
<?php
$host = "localhost";
$user = "myappuser";
$pass = "password";
$db = "myapp";
echo "\n test";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "SELECT * FROM app1_snippet";
$rs = pg_query($con, $query) or die("Cannot execute query: $query\n");
while ($row = pg_fetch_assoc($rs)) {
echo $row['id'] . " " . $row['name'] . " " . $row['phone_no']. " " . $row['status'];
echo "\n";
}
pg_close($con);
?>
</body>
</html>
Ya figured out how to do.
below is the Code.
<!DOCTYPE html>
<html>
<head>WELCOME</head>
<body style="background-color:#E4E5E7">
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
table#t01 {
width: 100%;
background-color: #f1f1c1;
}
</style>
</head>
<body>
<?php
$url= 'http://yoururltypehere.com';
$options = array(
'http' => array(
'header' => array(
'name: '.$_GET['name'],
),
'method' => 'GET',
),
);
$context = stream_context_create($options);
$output = file_get_contents($url, false,$context);
$arr = json_decode($output,true);
?>
<table style="width:100%">
<tr>
<th>ID</th>
<th>NAME</th>
<th>PHONE_NO</th>
<th>STATUS</th>
</tr>
<br>
<?php
for($x=0;$x<count($arr);$x++)
{
?>
<tr>
<td><?php echo $arr[$x]['id']; ?>
<td><?php echo $arr[$x]['name']; ?>
<td><?php echo $arr[$x]['ph_no']; ?>
<td><?php echo $arr[$x]['stats']; ?>
</tr>
<?php
}
?>
<br>
</table>
</body>
</html>

Image from database is not displaying on webpage

so I have this blog that I am creating, but I am having issues with displaying an image from a database to the page itself. It only comes up with a broken image. The data does appear in the database however. It just doesn't display on the page.
Here is the image.php code (used to display the text and images):
<html>
<body>
<?php
//connect to database
//Name the variables
$host= "localhost";
//Localhost is the name of the computer that USBWebser has been loaded on
$username = "user";
$password = "pwd";
$database = "blog";
$dbh=mysql_connect("$host", "$username", "$password") or die('Could not connect:' .mysql_error());
//if cannot connect to database display error message
if(!$dbh)
{
echo mysql_error();
}
mysql_select_db("$database");
//get the id number of the row that the photo is located in and place it in $ano
$ano=$_GET['postID'];
//select the data and type for the photo identified by id
$sql="SELECT photo, phototype FROM blog where postID='$ano'";
//check if sql query can be executed
$r=mysql_query($sql, $dbh);
//if sql query can be executed
if($r)
{
//get the data from the query
$row=mysql_fetch_array($r);
//set the header information so that an image can be displayed
$type="Content-type: image/png" .$row['phototype'];
header($type);
//display the image
echo $row['photo'];
}
else
{
echo mysql_error();
}
?>
Here is the code for the main_menu.php (where I would like the image to appear)
<?PHP
//Name the variables
$host= "localhost";
//Localhost is the name of the computer that USBWebser has been loaded on
$username = "user";
$password = "pwd";
$database = "blog";
$mysqli=new mysqli($host, $username, $password, $database);
//Connect to Header
include "header.php";
?>
<?php
//Select fields from the posts table
$sql="SELECT postID, title, date, contents, rating, photo, phototype FROM posts";
//Place the data into a variable named $result
$result= $mysqli->query($sql);
if ($result->num_rows>0){
while ($row=$result->fetch_assoc()) {
?>
<br><table border="1" bordercolor="25dae3" width="53%"><th><font color="white">Title</th><th><font color="white">Date</th><th><font color="white">Contents</th><th><font color="white">Image</th><th><font color="white">Rating</th>
<tr><td width = "100" align="center"><font color="white">
<?php
echo $row["title"];
?>
</td>
<br><td width="100" align="center"><font color="white">
<?php
echo $row["date"];
?>
</td>
<br><td width="300" align="center"><font color="white">
<?php
echo $row["contents"];
?>
</td>
<br><td width="300" align="center"><font color="white">
<img src="<?php echo $row['photo']; ?>" width=300 height=300/>;
</td>
<br><td width="100" align="center"><font color="white">
<?php
echo $row["rating"];
?>
</td></tr></font>
<?php
}
} else {
//Display message that no data was present
echo "0 results";
}
//Close connection
$mysqli->close();
?>
The add_post.php
<html>
<header>
</header>
<body>
<?php
//Name the variables
$host = "localhost";
//Localhost is the name of the computer that USBWebserver has been loaded on
$username = "user";
$password = "pwd";
$database = "blog";
$mysqli=new mysqli($host, $username, $password, $database);
//Get variables from the form
$new_post_title=$_POST["newtitle"];
$new_post_date=$_POST["newdate"];
$new_post_contents=$_POST["newcontents"];
$new_post_rating=$_POST["newrating"];
$photo=addslashes(file_get_contents($_FILES["photo"]["tmp_name"]));
$imagesize=getimagesize($_FILES["photo"]["tmp_name"]);
//mime returns the image time eg. image/jpeg
$imagetype=$imagesize['mime'];
//Enable sql to read quotation marks within sentences
$new_post_title=addslashes($new_post_title);
$new_post_date=addslashes($new_post_date);
$new_post_contents=addslashes($new_post_contents);
$new_post_rating=addslashes($new_post_rating);
//Enter the new information into the posts table
$sql="INSERT INTO posts(postID, title, date, contents, rating, photo, phototype) VALUES (Null, '$new_post_title', '$new_post_date', '$new_post_contents', '$new_post_rating', '$photo', '$imagetype')";
//Run the query
$result=$mysqli->query($sql) or die (mysqli_error($mysqli));
if ($result) {
header ('location:main_menu.php');
}
else {
echo mysql_error();
}
?>
</body>
</html>
And the form to submit a post to the blog (add_new_post.php)
<HTML>
<style>
form {
border-opacity: 1.0 ;
display: incline-block;
text-align: center;
}
input[type=text]:focus, input[type=date]:focus {
width: 50%;
height: 20%;
border: 3px solid #00ffff;
}
body {
text-align: center;
padding-top: 50px;
}
</style>
<HEAD>
</HEAD>
<BODY><font color="white">
<br><br><br><H1 text-align="center">Add a New Post</H1>
<?php
//Connect To Header Page
include "header1.php";
//Connect To Database
include "dbconnect.php";
?>
<br>
<br>
<!-- <HR> Tag inserts a horizonal line across the page (horizontal rule)-->
<!-- <Form> Tag indicates that a form will be created -->
<!-- action indicates the file used to process the input when the submit button is pressed-->
<form enctype= "multipart/form-data" action="add_post.php" method = "POST">
Title: <br>
<!-- <input type> Tag indicates the type of input expected eg. text. Name = indicates the name given to the input-->
<input type="text" name="newtitle"><br>
Date: <br>
<input type="date" name="newdate"><br>
Contents: <br>
<input type="text" name="newcontents"><br>
Rating: <br>
<input type="text" name="newrating"><br>
Please Browse to where the photo is located:<br>
<input type = file name = "photo"><br>
<br>
<!-- Value indicates the text to be displayed. In this case, displayed on the button -->
<input type ="submit" value="Submit">
</form>
</BODY>
</HTML>
Any assistance on this issue would be appreciated.
Thanks
You are using php tag wrong
<br><td width="300" align="center"><font color="white">
<?php
echo "<img src="<?php echo $row['photo']; ?>" width=300 height=300/>";
?>
</td>
instead of above code use following code
<br><td width="300" align="center"><font color="white">
<img src="<?php echo $row['photo']; ?>" width=300 height=300/>
</td>

Display an image from a MySQL database using PHP

New to this but loving it. I have a database of URLs of pictures of cats that I want to display in a webpage. I wrote some php to do this but all I'm seeing it the URL of the image and not the image itself. Here is my full code:
<html>
<body>
<h1>Katz!!</h1>
<!--Connect to Database-->
<?php
$db_host = "localhost";
$db_username = "Alex";
$db_pass = "";
$db_name = "cats";
#mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mySQL");
#mysql_select_db("$db_name") or die ("No database");
$sql="SELECT * FROM cats_test";
$records = mysql_query($sql);
?>
<!--Populate table from database-->
<table border="2" cellpadding="1" cellspacing="1">
<tr>
<th>cat table</th>
</tr>
<?php
while($cats_test=mysql_fetch_assoc($records)) {
echo "<tr>";
echo "<td>".$cats_test['image']."</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
As you can see, the database name is "cats" with a table called "cats_test" that holds all of the images in a column called "image" you can find a screenshot of that here
You can also see the URLs being displayed instead of images here
I've probably done something really stupid, so would appreciate any help you guys might have!!
Replace your :
echo "<td>".$cats_test['image']."</td>";
With :
echo "<td><img src='".$cats_test['image']."' ></td>";

Modify php script to populate SQL Server 2012

I have this php script that parses data from a regular url in the form of "http://example.com/board.php?username=John&score=15&session=976837465", places that in a simple MySQL db, then sorts the score to form a top 10.
Can someone help me with the code to do the same for a SQL Server 2012 db? Please assume that the db has already been created.
Note : I know the method above is insecure and not recommended, but at present it is the only way I am able to pass data over - trust me on this.
Please find the full php code below.
Thanks in advance,
John
<?php
$dbhost = 'localhost'; // Database Host Name - usually 'localhost'
$dbname = 'mydb'; // Database Name
$dbuser = 'myusername'; // Database User Name
$dbpass = 'mypassword'; // Database User Password
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname,$conn);
$game = 'My Game'; // The Name of your game
{
$name = urldecode(mysql_real_escape_string($_GET['username']));
$score = intval(mysql_real_escape_string($_GET['score']));
$gamesession = mysql_real_escape_string($_GET['session']);
global $tlb;
if (!empty($game) && !empty($name) && !empty($score) && !empty($gamesession)) {
$query = "INSERT INTO game_leaderboard (game, name, score, session)
VALUES('$game', '$name', '$score', '$gamesession')";
mysql_query($query) or trigger_error(mysql_error()." in ".$query);
}
}
?>
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Sansita+One'
rel='stylesheet' type='text/css'>
<link href="table.css" rel="stylesheet" type="text/css" media="all" />
</head>
<body>
<div role="main">
<header>
<h2 class="toptitle">My Game</h2>
</header>
<?php
$lboard = "SELECT * FROM game_leaderboard WHERE game = '$game' ORDER BY score DESC LIMIT 10";
$leaderboard = mysql_query($lboard) or trigger_error(mysql_error()." in ".$lboard);
?>
<table class="th">
<thead style="background:#f7f7f7;">
<tr>
<td style="font-size: 18px; width:30%;">Name</td>
<td style="font-size: 18px; width:70%;">Score</td>
</tr>
</thead>
<tbody style="background:#ffffff;border:1px solid #bfbfbf;">
<?php
$i=0;
while ($i < mysql_numrows($leaderboard)) { ?>
<tr style="border-bottom:1px solid #cccccc;">
<td><?php echo ucwords(mysql_result($leaderboard,$i,"name")); ?></td>
<td><?php echo mysql_result($leaderboard,$i,"score"); ?></td>
</tr>
<?php $i++; } ?>
</tbody>
</table>
</div>
</body>
</html>
PHP has made it easy to access data from any database, you can follow this guide i found here for ms sql servers http://www.easysoft.com/developer/languages/php/sql_server_unix_tutorial.html

session_start() causing page time out

I just started a project with a new client and have run into an issue that I haven't had before.
I've moved a copy of their site to my local machine (running the latest version of mamp) and I got their database set up with no issue.
The main pages load fine, but after I log in and am taken to the admin dashboard (a custom cms), clicking on any link causes the page to hang and timeout.
I've narrowed the issue down to the initial call to session_start() on the subpages and removing it and any code that references the session data allows the pages to load.
The site did not have a php.ini file.
I've googled around and found several suggestions of using session_write_close() at the end of each file, and before redirection. I've tried this and still get the timeout.
I've noticed that when I log in the session is created without issue in the mamp/tmp/php folder on my mac, and the dashboard page that loads can be refreshed (calling session_start() again) without the page timing out.
Also, once I try to load any other page in the admin (causing the timeout) I can no longer access the dashboard page because it begins to timeout to. I then have to delete the session file to regain access to any pages that start a session.
Here is the dashboard page code, I don't see anything in there that should cause the next page to load to have a session issue (I'm not looking for best-practices suggestions, I literally just inherited this codebase).
<?php
session_start();
if(basename($_SERVER['PHP_SELF'])!="index.php") {
if(!isset($_SESSION['is_logged_in'])) {
header("Location:index.php");
die();
}
}
?>
<!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" xml:lang="en" lang="en">
<head>
<title>RVC Admin: Dashboard</title>
<?php
include "includes/connect.php";
include "includes/headers.php";
?>
</head>
<body>
<div id='main'>
<?php
include "includes/menu.php";
?>
<h1>RVC Admin System</h1>
<?php
$result = mysql_query("SELECT COUNT(ID) as HOWMANY FROM listings");
if(#mysql_num_rows($result)>0) {
$row = mysql_fetch_assoc($result);
$LISTINGS = number_format($row['HOWMANY']);
}
$result = mysql_query("SELECT COUNT(id) as HOWMANY FROM user");
if(#mysql_num_rows($result)>0) {
$row = mysql_fetch_assoc($result);
$ADMINS = number_format($row['HOWMANY']);
}
print "<p>There are ".$LISTINGS." listings in the system, and ".$ADMINS." admins.</p>";
$result = mysql_query("SELECT description FROM LGBTlevel ORDER BY description");
if(#mysql_num_rows($result)>0) {
print "<div style='float: left; padding-right: 30px;'><p>Levels:</p>";
print "<ul style='margin: 2px 0 5px 18px; padding: 0;'>";
while($row = mysql_fetch_row($result)) {
print "<li style='margin-bottom: 2px;'>".$row[0]."</li>";
}
print "</ul></div>";
}
$result = mysql_query("SELECT description FROM LGBTtype ORDER BY description");
if(#mysql_num_rows($result)>0) {
print "<div style='float: left; padding-right: 30px;'><p>Types of Listings:</p>";
print "<ul style='margin: 2px 0 5px 18px; padding: 0;'>";
while($row = mysql_fetch_row($result)) {
print "<li style='margin-bottom: 2px;'>".$row[0]."</li>";
}
print "</ul></div>";
}
print "<br style='clear: left;' />";
?>
<?php session_write_close(); ?>
<br style='clear: both;' /><br />
</div>
</body>
</html>
Here is the connect.php file (actual access info removed)
<?php
$testing_server = true;
if($testing_server != true){
$MYSQL_USER_NAME = "removed";
$MYSQL_PASSWORD = "removed";
$MYSQL_DATABASE_NAME = "removed";
$dbh=mysql_connect ("localhost", "$MYSQL_USER_NAME", "$MYSQL_PASSWORD") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("$MYSQL_DATABASE_NAME");
$db = new mysqli('localhost', "$MYSQL_USER_NAME", "$MYSQL_PASSWORD", "$MYSQL_DATABASE_NAME");
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
} // if testing server != true
else{
$MYSQL_USER_NAME = "removed";
$MYSQL_PASSWORD = "removed";
$MYSQL_DATABASE_NAME = "removed";
$dbh=mysql_connect ("localhost", "$MYSQL_USER_NAME", "$MYSQL_PASSWORD") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("$MYSQL_DATABASE_NAME");
$db = new mysqli('localhost', "$MYSQL_USER_NAME", "$MYSQL_PASSWORD", "$MYSQL_DATABASE_NAME");
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
}//else, testing server credentials
?>
Here is the headers file
<meta name='robots' content='noindex,nofollow' />
<meta name='author' content='removed' />
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<meta name='MSSmartTagsPreventParsing' content='TRUE' />
<meta http-equiv='imagetoolbar' content='no' />
<link rel='stylesheet' type='text/css' href='css/styles.css' />
<link type="text/css" href="css/custom-theme/jquery-ui-1.9.1.custom.css" rel="stylesheet" />
<script type='text/javascript' src='includes/javascript/jquery-1.8.1.min.js'></script>
<script type="text/javascript" src="includes/javascript/jquery-ui-1.9.1.custom.min.js"> </script>
<link href='https://fonts.googleapis.com/css?family=Cantora+One' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Cabin+Condensed' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Roboto+Condensed' rel='stylesheet' type='text/css'>
Aaand here is the menu file
<?php
#MENU
?>
<form method='post' action='index.php' style='float: right; margin: 0 0 0 10px;'><input type='hidden' name='RVC_LOGOUT' value='TRUE' /><input type='image' title='Logout' src='images/icon-logout.png' /></form>
<a href='admin-users.php' title='Manage Users'><img src='images/icon-users.png' border='0' alt='Manage Users' style='float: right; margin: 0 0 0 10px;' /></a>
<a href='listings.php' title='Edit Listings'><img src='images/icon-listings.png' border='0' alt='Edit Listings' style='float: right; margin: 0 0 0 10px;' /></a>
<a href='dashboard.php' title='Home'><img src='images/icon-home.png' border='0' alt='Home' style='float: right; margin: 0 0 0 10px;' /></a>
If anyone can see any reason that this page should load fine the after logging in and then cause every page that uses a session to timeout after trying to leave it, your help would be appreciated.
clicking any link in the menu file causes the page to timeout at the first line, which as I said is the session_start();
EDIT:
I reduced one of the sub pages to just the session_start call and it still causes the browser to time out.

Categories