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
Related
I tried to add a delete "button"(link to file with function) it should delete a row from the database, but it didn't work. I looked for tutorials and answers on forums but found nothing how solve for my problem.
<td>Delete</td>
link from code:
The link works correctly, but when I tried to delete it just doesn't want to take 'commentId' variable and go back to test.php page
Table on website:
dbh.inc.php
<?php
$serverName = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "php-login";
$conn = mysqli_connect($serverName, $dBUsername, $dBPassword, $dBName);
if (!$conn){
die("connection failed: " . mysqli_connect_error());
}
test.php
<?php
include_once 'header.php';
include "includes/dbh.inc.php";
include 'includes/test.inc.php';
?>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="box">
<h4 class="display-4 text-center">Comments</h4><br>
<?php if (isset($_GET['success'])) { ?>
<div class="alert alert-success" role="alert">
<?php echo $_GET['success']; ?>
</div>
<?php } ?>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Username</th>
<th scope="col">Comment</th>
<th scope="col">Action</th>
</tr>
</thead>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<td><?php echo $row["commentId"]; ?></td>
<td><?php echo $row["usersUid"]; ?></td>
<td><?php echo $row["comment"]; ?></td>
<td>Delete</td>
</tr>
<?php
$i++;
}
?>
</table>
</div>
</div>
</body>
</html>
test.inc.php
<?php
include "dbh.inc.php";
$sql = "SELECT * FROM commenttb ORDER BY commentId DESC";
$result = mysqli_query($conn, $sql);
delete.inc.php
<?php
include "dbh.inc.php";
if(isset($_GET['commentId'])) {
$id = $_GET['commentId'];
$delete = "DELETE FROM `commenttb` WHERE `commentId` ='$id'";
$result = mysqli_query($conn, $delete);
if ($result) {
header("Location: ../test.php?success=successfully deleted");
} else {
header("Location: ../test.php?error=unknown error occurred");
}
}else {
header("Location: ../test.php?error=smth gone wrong");
}
If I press on the link "delete" it should take 'commentId' variable from row e.g. 5 and by SQL query from delete.inc.php file delete row with this id from my database
I tried change $_Get to $_POST and add method="POST" to link on delete.inc.php file, but it didn't work
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
I have reviewed, and edited, all the code previously discussed and it seems to be working fine now. Thanks very much for your help. Below is the last snippet that seems to be hanging the code:
print('N. of records: '.$result->num_rows.'<br />');
print('<table>');
while ($row = $result->fetch_object()){
print('<tr><td>'.$row['last'].'</td><td>'.$row['first'].'</td></tr>');
}
print('</table>');
I can not find an error in this snippet. As well, I can verify that the connection to the database is working because a test in the code shows that:
"N. of records: 5" were selected. Those 5 records all have data in the 'first' and 'last' fields. So, I think there must be an error in the code above which would not cause an error, but would also still cause the table to not be created. To be clear, the table is not just empty, it is not there at all.
Since the table is not being created, my guess was that the error must be in the print('<table>'); line, but for the life of me, I can't see an error in it. Can you?
It seems there are many errors in your code and also you didn't use the proper MySQLi functions. You should have some more research on the MySQLi with PHP and then it will be quite easy for you.
I refined your code have a look and try this:
<html>
<body>
<?php
$dbhost = 'localhost:3306';
$username = "root";
$password = "";
$database = "newworld";
$conn =mysqli_connect($dbhost, $username, $password, $database);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
} else {
#db connected
}
/**/
$sql = 'SELECT first, last FROM photos';
$result = mysqli_query($conn, $sql);
/**/
?>
<table border="1" cellspacing="2" cellpadding="2">
<tr>
<td><font face="Arial, Helvetica, sans-serif"><u>first</u></font></td>
<td><font face="Arial, Helvetica, sans-serif"><u>last</u></font></td>
</tr>
<?php
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $row["first"]; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $row["first"]; ?></td>
</tr>
<?php
}
} else {
echo "0 results";
}
?>
</table>
</body>
</html>
Note*: Update your database details like DB name, username, and password
I have a problem of data not being retrieved from database. It only echos the sentence that I typed instead of the data in my database. I've tried it for several times and it still does not work. Is there anything wrong with my code? Please help
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>database connections</title>
</head>
<body>
<?php
$username = "database-username";
$password = "database-password";
$host = "localhost";
$connector = mysqli_connect($host,$username,$password)
or die("Unable to connect");
echo "Connections are made successfully::";
$selected = mysqli_select_db($connector, "test_db")
or die("Unable to connect");
//execute the SQL query and return records
$result = mysqli_query("SELECT * FROM table_one ");
?>
<table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
<thead>
<tr>
<th>Employee_id</th>
<th>Employee_Name</th>
<th>Employee_dob</th>
<th>Employee_Adress</th>
<th>Employee_dept</th>
<td>Employee_salary</td>
</tr>
</thead>
<tbody>
<?php
while( $row = mysqli_fetch_assoc( $result ) ){
echo
"<tr>
<td>{$row\['employee_id'\]}</td>
<td>{$row\['employee_name'\]}</td>
<td>{$row\['employee_dob'\]}</td>
<td>{$row\['employee_addr'\]}</td>
<td>{$row\['employee_dept'\]}</td>
<td>{$row\['employee_sal'\]}</td>
</tr>\n";
}
?>
</tbody>
</table>
<?php mysqli_close($connector); ?>
</body>
</html>
You need below Changes in your Code :
1) Change these line :
$result = mysqli_query("SELECT * FROM table_one ");
To below line :
$result = mysqli_query($connector, "SELECT * FROM table_one ");
2) Change these lines :
<td>{$row\['employee_id'\]}</td>
<td>{$row\['employee_name'\]}</td>
<td>{$row\['employee_dob'\]}</td>
<td>{$row\['employee_addr'\]}</td>
<td>{$row\['employee_dept'\]}</td>
<td>{$row\['employee_sal'\]}</td>
To Below Lines :
<td>{$row['employee_id']}</td>
<td>{$row['employee_name']}</td>
<td>{$row['employee_dob']}</td>
<td>{$row['employee_addr']}</td>
<td>{$row['employee_dept']}</td>
<td>{$row['employee_sal']}</td>
That's It.
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>