Live update MySQL Data - php

I have the following code and it works great, I just want to convert it to live so it updates every 10 seconds or so without a page refresh, I'm guessing I'll need to use AJAX or Jquery but I lack the knowledge on how to do so.
=====VIA <?php include("database.php"); ?>====
<?php
// Create connection
$con=mysqli_connect("ip/host","user","pass","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
====ON THE PAGE====
<? php
$result = mysqli_query($con, "SELECT * FROM sql347511.1 ORDER BY ID DESC LIMIT 1;");
while ($row = mysqli_fetch_array($result)) {
echo "<div class='infobox_data'>Temperature: ".$row['TEMP']."°C</div>";
echo "<div class='infobox_data'>Humidity: ".$row['HUMID']."%</div>";
echo "<div class='infobox_time'>Captured: ".date("g:i:s a F j, Y ", strtotime($row["TIME"]))."</div>";
}
mysqli_close($con); ?>

Got it working, thanks for the help everyone.
Javascript
$(document).ready(function(){
loadstation();
});
function loadstation(){
$("#station_data").load("station.php");
setTimeout(loadstation, 2000);
}
station.php
<?php
include ("database.php");
$result = mysqli_query($con, "SELECT * FROM sql347511.1 ORDER BY ID DESC LIMIT 1;");
while ($row = mysqli_fetch_array($result))
{
echo "<div class='infobox_data' id='infobox_temp'>" . $row['TEMP'] . "°C</div>";
echo "<div class='infobox_data' id='infobox_humid'>" . $row['HUMID'] . "%</div>";
echo "<div class='infobox_time'>At " . date("g:i:s a F j, Y ", strtotime($row["TIME"])) . "</div>";
}
mysqli_close($con);
?>
Where to put the data
<div id="station_data"></div>

You can make inputs from div on double click and then get this inputs value through jquery:
$().val;
then using ajax send this value to php:
$.ajax({
url: 'url_to_php_which_update_mysql',
data: {'data': 'value_from_input'},
cache: false,
success: function(response){
$(input).val(response);
}
});
And in php file you need to upload $_GET['data'] in Database

Related

Error with PHP validation

I am creating a basic auction site and got quite far with help from this community. I am near finishing this now but having a slight issue with server side validation.
Auctions are listed on a PHP page with html and PHP, PHP runs a MySQL query and then lists the results. Example here:
$result = mysqli_query($con,"SELECT * From auction WHERE category = 'Bathroom' ORDER BY ID DESC");
while($row = mysqli_fetch_array($result))
{
echo "<form name='auction' id='auction" . $row['ID'] . "'>
<input type='hidden' name='id' value='" . $row['ID'] . "' />
<div class='auction-thumb'>
<div class='auction-name'>" . $row['Item'] . "</div>";
echo "<img class='auction' src='" . $row['ImagePath'] . "' />";
echo "<div class='auction-bid'>Current Bid: £<div class='nospace' id='" . $row['ID'] . "'>" . $row['CurrentBid'] . "</div></div>";
echo "<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname' autocomplete='off'/></div>";
echo "<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid' autocomplete='off'/></div>";
echo "<div class='auction-bid'><input type='submit' name='submit' value='Place Bid!' /></div>";
echo "<div class='bid-success' id='bid" . $row['ID'] . "'>Bid placed!</div>";
echo "</div></form>";
}
echo "</table>";
mysqli_close($con);
Once the user clicks the submit button, the following jQuery is executed:
$(document).ready(function(){
$('form[name="auction"]').submit(function(){
var id = $(this).find('input[name="id"]').val();
var bidname = $(this).find('input[name="bidname"]').val();
var bid = $(this).find('input[name="bid"]').val();
var currentbid = $('#'+id).text();
var itemdesc = $(this).find('.auction-name').text();
bid = parseFloat(parseFloat(bid).toFixed(2));
currentbid = parseFloat(parseFloat(currentbid).toFixed(2));
if (bidname == '')
{
alert("No name!")
return false;
}
/* if (bid > currentbid)
{
alert("Bid is greater than current bid");
}
else
{
alert("Bid is too low!");
return false;
}*/
$.ajax({
type: "POST",
url: "auction-handler.php",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id, itemdesc: itemdesc},
success: function(data){
$('#bid'+id).fadeIn('slow', function () {
$(this).delay(1500).fadeOut('slow');
});
//$('#auction' + id).find('.nospace').html(currentbid);
},
error: function() {
alert("bid too low");
}
});
return false;
});
});
If the code POSTS, the following PHP code is run on the handler page:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$bidname = $_POST['bidname'];
$bid = $_POST['bid'];
$id = $_POST['id'];
$itemdesc = $_POST['itemdesc'];
$highestbid = mysqli_fetch_row(mysqli_query($con,"SELECT CurrentBid from Auction WHERE ID = '$id'"));
if ($bid <= $highestbid)
{
$_SESSION['errors']['bid'] = 'Sorry, but the bid is too low';
echo json_encode($_SESSION['errors']);
exit;
}
else
{
$query = "UPDATE auction SET CurrentBid = '$bid', Bidder = '$bidname' WHERE ID = '$id'";
$query2 = "INSERT INTO auction_log (Item, Bid, Bidder) VALUES ('$itemdesc','$bid','$bidname')";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_query($con, $query2) or die(mysqli_error());
mysqli_close($con);
I added some server side validation to make sure that the bid posted is higher than what is currently in the MySQL table.
The problem I am having is that I get the "Sorry, but the bid is too low" error no matter what bid I put in.
If I put a bid higher than the current bid, I get the error, if I put a bid in lower, I get the error.
Both ways I go about it also trigger the success section of the AJAX.
I feel like I'm missing something very simple, so if anyone could help that would be great.
I am not sure why it's being downvoted, I am just looking for some help.
Thanks
The way that you're handling AJAX error is not very good because it only alerts you that you have an error, but you don't know what goes wrong.
In the AJAX object, replace the current error callback with one that logs the actual error to the console:
replace
error: function() {
alert("bid too low");
}
with
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
and you'll know for sure what is the error

Reload PHP include without innerHTML

When someone on my Minecraft server sends a chat message, a plugin sends that message to a listener.php file, which enters the info into a Mysql database. I am trying to display it in real time (well, as close as possible) in the admin panel I am building for the website. While using .load works as far as getting the content on the page, it breaks the jquery-operated scrollbars I have on the chatbox, making it where you can't scroll down through the posts. This is because it has to have enough 's to warrant the need for scrolling before the scrollbar will appear, but with the .load, the only present is the that the contents of chat.php are being loaded into. the only way I can get the chat to work is including the chat.php with a php include, with chat.php looking like:
<?php
echo "<div class='block messages scrollBox'><div class='scroll' style='height: 320px;'> ";
$con=mysqli_connect("localhost","bduser","pass","dbase");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM server_chat ORDER BY date DESC , time DESC LIMIT 15");
while($row = mysqli_fetch_array($result)) {
$user = $row['user'];
$message = $row['message'];
$date = $row['date'];
$time = $row['time'];
echo "<div class='item clearfix'><div class='image'><a href='#'><img src='../face.php?u=$user' class='img-polaroid' /></a></div><div class='info'><a class='name' href='#'>$user</a><p>$message</p> <span>$time $date</span></div></div>";
}
mysqli_close($con);
echo "</div></div>";
?>
How do I keep the above format for displaying the contents of the chat table on my database, but update it every 5 seconds or so? Is there a way to automatically re-query the database? While code snippets help, I in the learning process, either pointing me in the right direction via q link to what method to use, or telling me what needs to be done and leaving the coding up to me would help much more in the long run. Thanks in advance!
NOTE: copy that php code too, i change it
Try this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
var interval = setInterval(function() {
$.ajax({
url: 'chat_reload.php',
success: function(data) {
$('#toreload').html(data);
}
});
}, 1000);
});
</script>
<?php
echo "<div class='block messages scrollBox'><div class='scroll' style='height: 320px;'><div id='toreload'> ";
$con=mysqli_connect("localhost","bduser","pass","dbase");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM server_chat ORDER BY date DESC , time DESC LIMIT 15");
while($row = mysqli_fetch_array($result)) {
$user = $row['user'];
$message = $row['message'];
$date = $row['date'];
$time = $row['time'];
echo "<div class='item clearfix'><div class='image'><a href='#'><img src='../face.php?u=$user' class='img-polaroid' /></a></div><div class='info'><a class='name' href='#'>$user</a><p>$message</p> <span>$time $date</span></div></div>";
}
mysqli_close($con);
echo "</div></div></div>";
?>
AND:
There in folder, where is this PHP code make new file with name chat_reload.php and put there this code:
<?php
$con=mysqli_connect("localhost","bduser","pass","dbase");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM server_chat ORDER BY date DESC , time DESC LIMIT 15");
while($row = mysqli_fetch_array($result)) {
$user = $row['user'];
$message = $row['message'];
$date = $row['date'];
$time = $row['time'];
echo "<div class='item clearfix'><div class='image'><a href='#'><img src='../face.php?u=$user' class='img-polaroid' /></a></div><div class='info'><a class='name' href='#'>$user</a><p>$message</p> <span>$time $date</span></div></div>";
}
mysqli_close($con);
?>

php updates database data only sometimes

I have to following form
$connection = mysqli_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD, SQL_DBNAME) ;
if (mysqli_connect_errno($connection))
{
echo "Nespojeno s MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM novinky";
$result = mysqli_query($connection, $sql);
echo "<div id='newsbox'>";
while($zaznam = mysqli_fetch_row($result)):
echo "<form class='newsholder'>";
echo "<input id='displaynadpis' value='$zaznam[1]'>";
echo "<input id='displaybold' value='$zaznam[2]'>";
echo "<textarea id='displaytext'>$zaznam[3]</textarea>";
echo "<div class='buttonsholder'>";
echo "<button class='deletebutton'>Smazat</button>";
echo "<button class='updatebutton'>Upravit</button>";
echo "<input id='prime' type='hidden' attr='id' value='$zaznam[0]'>";
echo "</div>";
echo "<div class='clearfix'></div>";
echo "</form>";
endwhile;
echo "</div>";
mysqli_close($connection);
that displays data from the database in order to update them upon the .updatebutton click.
The data is passed by jquery ajax
$('.updatebutton').on('click', function(){
var idVal = $(this).closest('.newsholder').find('#prime').val();
var displaynadpisVal = $(this).closest('.newsholder').find('#displaynadpis').val();
var displayboldVal = $(this).closest('.newsholder').find('#displaybold').val();
var displaytextVal = $(this).closest('.newsholder').find('#displaytext').val();
alert(displaynadpisVal);
$.ajax({url:"updaterecord.php",
type:"POST",
cache:false,
data:{id: idVal, displaynadpis: displaynadpisVal, displaybold: displayboldVal, displaytext: displaytextVal}
}); });
to the php script
$connection = mysqli_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD, SQL_DBNAME) ;
if (mysqli_connect_errno($connection))
{
echo "Nespojeno s MySQL: " . mysqli_connect_error();
}
$id = $_POST['id'];
$updatenadpis = $_POST['displaynadpis'];
$updatetextbold = $_POST['displaybold'];
$updatetext = $_POST['displaytext'];
echo $updatetext;
$sql = "UPDATE novinky SET nadpis='$updatenadpis',
textbold='$updatetextbold',
text='$updatetext'
WHERE id = '$id'"
;
$retval = mysqli_query($connection, $sql);
if(! $retval )
{
die('Could not enter data: ' . mysqli_connect_error());
}
echo "Entered data successfully\n";
mysqli_close($connection);
to update the database. The problem is, that it only works sometimes, but in about 70% of cases it doesn't make any change. The data is stored in js variables just fine, when tested by alert(), they exist everytime. So the problem must be in the mysqli_query() possibly? Or the AJAX method? I have tried a lot of options and recommendations from other posts but no luck. Thanks for your help...
Biggest problem here is fact that you are passing raw user input to query. Assigning it to variable doesn't change anything!
You should filter everything received from user and use prepared statements to be sure that you are safe.
Also don't use mysqli_connect_error() to check query errors. Use mysqli_error().

Dynamic drop down menus

I want to create a dynamic drop down where the options of the second drop down changes after the selection of the first drop down.
The test.php file
<?php
$con=mysqli_connect("localhost","******","****","******");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM countries");
?>
<select id="country" name='country' onchange="get_states();">
<option value=''>Select</option>
<?php
while($row = mysqli_fetch_array($result))
{
echo "<option value='" . $row['country_id'] . "'>" . $row['country_name'] . "</option>";
}
?>
</select>
<div id="get_state"></div> // Sub will be appended here using ajax
<script type="text/javascript">
function get_states() { // Call to ajax function
var country = $('#country').val();
var dataString = "country="+country;
$.ajax({
type: "POST",
url: "getstates.php", // Name of the php files
data: dataString,
success: function(html)
{
$("#get_state").html(html);
}
});
}
</script>
<?php
mysqli_close($con);
?>
and the gestates.php is:
<?php if ($_POST) {
$country = $_POST['country'];
if ($country != '') {
$sql1 = "SELECT * FROM states WHERE country_id=" . $country;
$result1 = mysql_query($sql1);
echo "<select name='state'>";
echo "<option value=''>Select</option>";
while ($row = mysql_fetch_array($result1)) {
echo "<option value='" . $row['id'] . "'>" . $row['state_name'] . "</option>";}
echo "</select>";
}
else
{
echo '';
}
}
?>
However the above code does not work!
on change on first drop-down you need to make an ajax call which will get the options and you can then populate the next drop-down
Try adding single quotes around $country
$sql1 = "SELECT * FROM states WHERE country_id='" . $country . "'";
or
$sql1 = "SELECT * FROM states WHERE country_id='$country'";
EDIT: Also, you can only echo one result. Your second echo will be ignored by Jquery as the first will be considered a success.
You should format your results differently.
Perhaps a json encoded array.
In your php:
while($row = mysql_fetch_array($result1))
{
$data[$row['id']] = $row['state_name'];
}
echo json_encode($data);
In your Jquery set dataType: 'json'
$.each(html,function(key,value){
$("#get_state").append($('<option>',{
value:key,
text: value
}));
});

how i can insert data in mysql and retrieve simulteneously in php on the click of one button?

actually i want to send a comment to the each image and it should display just after clicking the button . I am able to do insert and retrieve the comment but it require refresh the page and i don't want to refresh....just like orkut.plz help me i m new in php...
thans to all............
insertimg.php
//________________________________________FOR INSERT COMMENT_____________________________________________________
if (isset($_POST['Submit']))
{
$sql = "INSERT INTO comment(imid, comm) values ('".mysql_real_escape_string(stripslashes($_REQUEST['imgId']))."', '".mysql_real_escape_string(stripslashes($_REQUEST['Comment']))."')";
//$sql = "INSERT INTO comment (com) VALUES ($_POST['Comment'])";
//$sql="UPDATE upload SET comm='$_REQUEST['Comment']'WHERE id='$_REQUEST['imgId']'";
if($result = mysql_query($sql ,$conn))
{
echo "submited:";
}
else
{
echo "<h1>problem </h1> ".mysql_error();
}
}
For display comment..
$page=$_GET["page"];
$sql = "select comm from comment where imid = '".$page."'";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo"Comments:";
echo "<br>";
echo "<br>";
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
//echo $row['comm'];
echo "<textarea name=\"Comment\" style=\"background-color:#81F7BE;\">"; echo $row['comm']; echo "</textarea>";
//echo "<font>";
echo "<br>";
echo "<br>";
}
mysql_close($conn);
?>
You can solve it with AJAX.
You can use something like jQuery Ajax library.
$.ajax({
type: "POST",
url: "inserting.php",
data: "imid=1&comm=Hi",
success: function(msg){
alert( "Ajax Response: " + msg );
}
});

Categories