AJAX Refresh - Duplicates already loaded Data from Database - php

On the current page I've been working on, I've set the code out in a way that it would work as a live blog / update kind of system. The problem is, I load the stuff in from my database in my PHP, then I have AJAX which links to another file which will get the database content and refresh the area it is contained in on my site.
Thus' meaning it will auto-update every 15000 miliseconds with the data from the database. The Problem is, it already has the existing data loaded in. So no matter what. every 15000 milisecond it will refresh that div, so data that is already on the page will be duplicated.
More Clear Bulletpoint form
PHP queries database, echo's out the data.
AJAX checks another php page every 15000 miliseconds and echo's that out onto the first page.
Instead of only posting new content, it simply duplicates the original content. (Can have double posts or even tripple. It seems to vary)
I'm only really getting into PHP, I haven't put much time into it, and my knowledge of AJAX is non-exisistant so it presents problem doing something like this. I've tried searching on how to only echo out the existing data on page one, even though page two is handling the updates.
Here is the code however, sorry if it's messy, or does things in correctly. I am still learning this language.
First Page matchdayupdates.php?id=(in this case the id is 6)
$id = $_GET['id'];
if(isset($_GET['id'])) {
$requestMatchInformation = mysqli_query($connect, "SELECT * FROM matchinfo WHERE pageid='$id' LIMIT 500");
while ($row = mysqli_fetch_assoc($requestMatchInformation)) {
$pageid = $row['pageid'];
$type = $row['type'];
$postheader = $row['postheader'];
$postcontent = $row['postcontent'];
$posttime = $row['posttime'];
echo "<div class='center-match-container'>
<div class='match-information'>
<div class='post-container'>
<div class='post-left'>
<img class='post-type-icon' src='images/icons/$type' />
</div>
<div class='post-right'>
<h3 class='header-top'>$postheader</h3>
<span class='time-red-right'>$posttime</span>
<br />
<br />
<p class='post-content'>$postcontent</p>
</div>
</div>
</div>
</div>";
}
$requestEventsInformation = mysqli_query($connect, "SELECT * FROM events WHERE id='$id'");
while($row = mysqli_fetch_assoc($requestEventsInformation)) {
$opponent = $row['opponent'];
$datetime = $row['datetime'];
$datetimedisplay = $row['datetimedisplay'];
$location = $row['location'];
$datepassed = $row['datepassed'];
$rowonescore = $row['rowonescore'];
$rowtwoscore = $row['rowtwoscore'];
$rowoneplayers = $row['rowoneplayers'];
$rowtwoplayers = $row['rowtwoplayers'];
}
}
else {
}
if(!$requestEventsInformation && !$requestMatchInformation) {
echo '<div class="match-notice"><h4>There are currently no updates, this page will auto-update when there are new updates.</h4></div>';
}
echo $id;
?>
<script>
var auto_refresh = setInterval(function () {
$('.center-match-container').fadeOut('slow', function() {
$(this).load('/esports/match/matchinforequest.php?id=<?php echo $id; ?>', function() {
$(this).fadeIn('slow');
});
});
$.ajaxSetup({ cache: true });
}, 15000);
</script>
Second Page matchinforequest.php?id=(again this id is 6)
$id = $_GET['id'];
if(isset($_GET['id'])) {
$requestMatchInformation = mysqli_query($connect, "SELECT * FROM matchinfo WHERE pageid='$id' LIMIT 500");
while ($row = mysqli_fetch_assoc($requestMatchInformation)) {
$pageid = $row['pageid'];
$type = $row['type'];
$postheader = $row['postheader'];
$postcontent = $row['postcontent'];
$posttime = $row['posttime'];
echo "<div class='center-match-container'>
<div class='match-information'>
<div class='post-container'>
<div class='post-left'>
<img class='post-type-icon' src='images/icons/$type' />
</div>
<div class='post-right'>
<h3 class='header-top'>$postheader</h3>
<span class='time-red-right'>$posttime</span>
<br />
<br />
<p class='post-content'>$postcontent</p>
</div>
</div>
</div>
</div>";
}
$requestEventsInformation = mysqli_query($connect, "SELECT * FROM events WHERE id='$id'");
while($row = mysqli_fetch_assoc($requestEventsInformation)) {
$opponent = $row['opponent'];
$datetime = $row['datetime'];
$datetimedisplay = $row['datetimedisplay'];
$location = $row['location'];
$datepassed = $row['datepassed'];
$rowonescore = $row['rowonescore'];
$rowtwoscore = $row['rowtwoscore'];
$rowoneplayers = $row['rowoneplayers'];
$rowtwoplayers = $row['rowtwoplayers'];
}
echo "Received Data";
}
else {
}

The problem is that you are loading the new data into any HTML element with the class center-match-container, but the new data you get with AJAX also contains an element with the class center-match-container, so the second call loads it into two places and so on.
In matchinforequest.php remove <div class='center-match-container'> and the corresponding </div> and it should work.
As a side note, you are not using prepared statements, but instead putting the contents of $_GET['id'] directly into your database query. This means someone could easily wipe your database by setting id to something like 0'; DELETE FROM matchinfo; '. Please look into prepared statements http://php.net/manual/en/mysqli.prepare.php and update your code to avoid this security risk!

Related

User value used instead of PHP value in textbox

I have a webpage thats purpose is to edit entries from a database. Its populated using PHP but i need the user to be able to change the value in these and update the database with the new value.
The problem im having is when i POST the data back from the form to the data base, the new information is NOT used, instead the PHP is. How do i fix this?
Each dropdown, text box and text field is populated from the text box using php:
<div class="col-lg-6">
<div class="form-group">
<label>Version</label>
<input type="text" class="form-control" name="forensic_tool_version" placeholder="Version" value="<?php
$session_name = $_SESSION['first_name']." ".$_SESSION['surname'];
$sql_query = "SELECT fi_forensic_tool_ver FROM asset_tracker WHERE asset_id = ? LIMIT 1";
$db_field = "fi_forensic_tool_ver";
$asset_id = $_GET['assetid'];
get_db_field($mysqli, $sql_query, $db_field, $asset_id, $session_name);
?>"/>
</div>
The get_db_field just gets the data and echos it to screen. This all works.
The user will then change one or more fields and click submit, where the following update will occur:
<!-- DATABASE INPUT - Input form elements into database -->
<?php
if(!empty($_GET['requestor']) ){
$asset_id = $_GET['assetid'];
$add_requestor = $_GET['requestor'];
$add_kc_number = $_GET['kc_number'];
$add_project_name = $_GET['project_name'];
$add_custodian = $_GET['custodian'];
$add_business_area = $_GET['business_area'];
$add_task = $_GET['task'];
$add_utl_reference = $_GET['utl_reference'];
$add_purchase_price_value = $_GET['purchase_price_value'];
$add_request_date = $_GET['request_date'];
$add_return_date = $_GET['return_date'];
$add_device_type = $_GET['device_type'];
$add_manufacturer = $_GET['manufacturer'];
$add_username = $_GET['username'];
$add_model = $_GET['model'];
$add_pinOrPassword = $_GET['pinOrPassword'];
$add_vf_asset_num = $_GET['vf_asset_num'];
$add_serial_num = $_GET['serial_num'];
$add_imei = $_GET['imei'];
$add_forensic_tool = $_GET['forensic_tool'];
$add_forensic_tool_version = $_GET['forensic_tool_version'];
$add_bitlocker_key = $_GET['bitlocker_key'];
$add_image_verified = $_GET['image_verified'];
$add_case_notes = $_GET['case_notes'];
$add_case_photos = $_GET['case_photos'];
if($query = $mysqli->prepare("UPDATE asset_tracker SET ci_requesting_employee=?, ci_kc=?, ci_project_name=?, ci_custodian=?, ci_business_area=?, ci_task=?, ci_utl_reference=?, ci_purchase_price_value=?, ci_date_requested=?, ci_date_returned=?, di_type=?, di_manufacturer=?, di_model=?, di_username=?, di_password=?, di_vf_asset=?, di_serial=?, di_imei=?, fi_forensic_tool=?, fi_forensic_tool_ver=?, fi_bitlocker_key=?, fi_image_verified=?, cn_notes=?, cn_photos=? WHERE asset_id = ? LIMIT 1")){
$query->bind_param('ssssssssssssssssssssssssi', $add_requestor, $add_kc_number, $add_project_name, $add_custodian, $add_business_area, $add_task, $add_utl_reference, $add_purchase_price_value, $add_request_date, $add_return_date, $add_device_type, $add_manufacturer, $add_username, $add_model, $add_pinOrPassword, $add_vf_asset_num, $add_serial_num, $add_imei, $add_forensic_tool, $add_forensic_tool_version, $add_bitlocker_key, $add_image_verified, $add_case_notes, $add_case_photos, $asset_id);
$query->execute();
$query->close();
echo "<script type='text/javascript'>alert('Asset updated Successfully');</script>";
}else{
echo "<script type='text/javascript'>alert('Cannot access database');</script>";
}
}else{
//echo "<script type='text/javascript'>alert('Post not set');</script>";
}
?>
Any help on this would be much appreciated!
Thanks!

How to remove a row from MySQL table data using html delete button in PHP

I am working on a project, for school. I currently have a product page to display an assortment of item includes image, description and price etc...
Under each product I have a delete button, when logged in as admin, which displays fine.
if (is_admin())
echo '<button>Delete item</button>'; }
I want to know how remove the row of data from MySQL table on clicking the delete button.
<?php
// Include need php scripts
require_once ("Includes/simplecms-config.php");
require_once ("Includes/connectDB.php");
include ("Includes/header.php");
if (!empty($_GET['cat'])) {
$category = $_GET['cat'];
$query = mysqli_query($db, "SELECT * FROM products WHERE category = '".$category."'");
} else {
$query = mysqli_query($db, "SELECT * FROM products");
}
if (!$query) {
die('Database query failed: ' . $query->error);
}
$deleted = mysql_query($db, "DELETE FROM products");
?>
<section>
<div id="productList">
<?php
$row_count = mysqli_num_rows($query);
if ($row_count == 0) {
echo '<p style="color:red">There are no images uploaded for this category</p>';
} elseif ($query) {
while($products = mysqli_fetch_array($query)){
$file = $products['image'];
$product_name = $products['product'$];
$image_id = $products['id'];
$price = $products['price'];
$desc = $products['description'];
echo '<div class="image_container">';
echo '<a href="viewProduct.php?id=' . $image_id . '"><p><img src="Images/products/'.$file.'" alt="'.$product_name.'" height="250" /></p>';
echo '' . $product_name ."</a><br>$" . $price . "<br>" . $desc;
echo '</div>';
if (is_admin()){
echo '<button>Delete item</button>';
}
}
} else {
die('There was a problem with the query: ' .$query->error);
}
mysqli_free_result($query);
?>
</div>
</section>
<?php include ("Includes/footer.php"); ?>
<!-- end snippet -->
You should post to a url with the id in the post data, then redirect back to where you were.
<?php
//html on productpage
if(isset($_GET['product_deleted'])){
if($_GET['product_deleted'] === 'true'){
echo 'The product was deleted';
}else{
echo 'The product could not be deleted';
}
}
if (is_admin()){
/**
* It's a good idea for the page that deletes to be different from the one your on, so that when you redirect back,
* they can refresh the page without getting something
* along the lines of 'refreshing with page will re-post the data'
*/
?>
<form method="POST" action="/product/delete.php">
<button>Delete item</button>
<input type="hidden" name="id" value="<?php echo $image_id; ?>" />
</form>
<?php
}
//PHP on /product/delete.php
if(is_admin() && $_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['id'])){
//delete sql here
header('Location: /productpage.php?product_deleted=true'); //redirect back
}
One approach
Change the button to a a element and make the href look like this:
yourdomain.tld/products/delete/{id}
You have to echo the primary key from your mysql database at the id position. It will look like this:
yourdomain.tld/products/delete/5
Then you have to change your .htaccess in a way that all requests go to your index.php in your root project. At the index.php you can do the actually query then.
Update
Keep in mind that anyone visiting this URL can delete products with this approach. You have to make sure that only the admin can do that. The preferred method is a POST request.
You can also send the primary key parameter to your PHP script you are just showed. With this approach you don't need to edit your .htaccess. You may pass it as an URL parameter like this:
yourdomain.tld/your-script.php?delete-product={id}
In your script you can get the parameter like this:
<?php
if (isset($_GET['delete-product'])) {
// your mysql query to delete the product
} else {
// something else
}
If you want to delete the entire row of an record from your db you can do like this. So that you can pass the product id and delete the row. Just bind the id with query using bind parameters concept
$knownStmt=mysqli_prepare($conn, "DELETE FROM `YourTableName` WHERE `pdt_id` = ?;");
if( $knownStmt ) {
mysqli_stmt_bind_param($knownStmt,"d",$pdt_id);
mysqli_stmt_execute($knownStmt);
mysqli_stmt_close($knownStmt);
}

show all users projects stored in the database

i am making a profile.php page and i would like it to show the user all his projects, this is my first time doing something like this, and i cant find a solution for it
code to show the projects :
$username = $_SESSION['username'];
if ($_SESSION['type'] = "developer"){
$q = "SELECT * FROM `projects` WHERE `developer` = '$username'";
$result = mysqli_query($con,$q);
$row = mysqli_fetch_array($result);
$numrows = mysqli_num_rows($result);
if(empty($numrows)){
echo'
<div class="row">
<div class="col-lg-12 newp">
<p><span class="glyphicon glyphicon-plus plus"></span>Add a new project</p>
</div>
</div>';
}else{
$p_id = $row['project_id'];
$p_name = $row['project_name'];
$p_owner = $row['owner'];
$p_developer = $row['developer'];
$p_price = $row['price'];
$p_date_started = $row['date_started'];
$p_date_end = $row['date_end'];
$p_paid = $row['paid'];
//foreach project the user has do this :
echo"
<div class=\"row\">
<div class=\"col-lg-12\">
<p>$p_name </br>owner : $p_owner, developer : $p_developer, price : $p_price$</br>started : $p_date_started, ends :$p_date_end, paid :$p_paid</p>
</div>
</div>";
}
}
} else {
while($row = mysqli_fetch_array($result)) {
$p_id = $row['project_id'];
...
Besides the other answer given:
You're presently assigning instead of comparing with
if ($_SESSION['type'] = "developer"){...}
^
which the above will fail and everything inside that conditional statement and should read as
if ($_SESSION['type'] == "developer"){...}
^^
with 2 equal signs.
Make sure the session has also been started, it's required when using sessions.
session_start();
You're also open to an SQL injection. Use a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement

trying to use combobox populated from mysql to send the $id to a second page to be used in a query

Trying to use ComboBox populated from mysql to send the $id to a second page to be used in a query to populate data.
Here is my code sitting in the bootsrap nav bar on page 1
<form class="navbar-form navbar-left" action='customerpage.php' method='post'>
<div class="form-group">
<select type="submit" id="navbarcustomer" class="form-control" name='customerid' placeholder="Customer Lookup">
<option>Customer Lookup</option>
<?php
require ('dbconnect.php');
$result = $con->query("select id, lastname, firstname from customer");
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$name = $row['lastname'];
$firstname = $row['firstname'];
echo '<option value="/customerpage.php?id='.$id.'">'.$name.','.$firstname.'</option>';
}
echo "</select>";
mysqli_close($con);
?>
</div>
</form>
here is my code on page to that needs to receive the $id variable to be used in the query
<?php
$id = $_GET['custid'];
echo $id;
require ('dbconnect.php');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM customer WHERE id=' . $id . '");
//$result = mysqli_query($con,"SELECT * FROM customer WHERE id=$id");
while($row = mysqli_fetch_array($result)) {
echo $row['firstname'];
echo "<br>";
}
?>
Please help the name of page 2 is /customerpage.php Thank you.
It looks like you've set it up so that when you click the dropdown, it will automatically go to the customers page. We will need just a little bit of JavaScript for that.
Place this below your closing </form> tag, but preferably right before you closing </body> tag document.
<script>
var navbarcustomer = document.getElementById('navbarcustomer');
navbarcustomer.addEventListener('change', function (e) {
window.location = this.value;
});
</script>
If you're using jQuery, you can OPTIONALLY use this in your <script> tags instead of the code above:
$('#navbarcustomer').on('change', function () {
window.location = $(this).val();
});
Next, you need to make sure your GET vars match what you're sending it. Change $_GET variable to look like this, as you are providing id= in the query string (and not custid=):
$id = $_GET['id'];
Edit:
There are a few more things that need to be addressed. Also in the customerpage.php, your query is little broken. You can use something like to fetch your records, it's a little bit cleaner:
$id = (int) $id; // cast to integer to prevent SQL injection.
$result = $con->query("SELECT * FROM customer WHERE id = $id");
// there is only going to be 1 record so we don't need the while loop.
$row = $result->fetch_assoc();
echo $row['firstname'];
echo $row['lastname'];

.load() When loaded page change

here is my problem - i have Div with include "file.php" with content of Database then i Insert new data to database and want to reload .load() file.php to div but content is same until i refresh the page. Someone who know what it is ?
File.php
<?php
include "../lib/dbconnect.php";
$class = $_GET['class'];
$get_posts = mysql_query("SELECT content, date, author, author_id FROM classPosts WHERE class = '$class' ORDER BY id DESC");
while (list($content, $time, $author, $author_id) = mysql_fetch_row($get_posts)){
$get_user_name = mysql_query("SELECT name, lastName FROM users WHERE nick = '$author'");
while (list($name, $lastName) = mysql_fetch_row($get_user_name)){
$time = new Cokidoo_DateTime("#" . $time);
echo "
<div class=\"div\">
<div class=crop-small title=\"$author\">
<a href=/user/user.php?user=$author_id><img src=/user/pics/$author_id.jpg class=img-small></a>
</div>
<span class=small-text><b style=\"color: rgb(100,100,100)\">$name $lastName</b><br>
<span class=\"small-text\">Přezdívka <b style=\"color: rgb(100,100,100)\">$author</b></span><br>
Přidáno $time</span><p><br></p>
<span class=\"small-text\">$content</span>
</div>
";
}
}
?>
there is Javascript
if(data.success)
{
$("#class_posts").fadeOut(function(){
$("#new_post").hide(0);
$("#class_posts").load("../trida/get_posts.php");
$("#class_posts").fadeIn();
$("#new_post_text").html("");
});
}
try appending a random number on the end as a query string - to prevent caching.
var randNum = Math.floor(Math.random() * 999999);
$("#class_posts").load("../trida/get_posts.php?"+randNum);

Categories