Refresh database rows & display without reloading page - php

I need to update database rows and display the change without reloading the page.
This is what I use currently to display the information:
<?php
$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$query = "SELECT * FROM craffyposts ORDER by time DESC $limit";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['like']; // This is what needs to be changed when database is updated.
?>
<?php
};
?>
like.php:
<?php
$cid = $_GET['id'];
database_connect();
$query2 = "SELECT * FROM craffyposts WHERE id = '".$cid."'";
$result2 = mysql_query($query2) or die(mysql_error());
while ($row2 = mysql_fetch_assoc($result2)) {
$lk = $row2['like'];
};
$nlk = $lk + "1";
mysql_query("UPDATE craffyposts SET `like` = '".$nlk."' WHERE id = '".$cid."'") or die(mysql_error());
echo "<script type='text/javascript'>window.location='index.php';</script>";
?>
Any help?

Without reloading the page? You'll have to use a client-side request to fetch new data from the server. the most common of such would be JavaScript's AJAX. You can use AJAX to fetch data from the server (presumably in some quickly parsed format such as JSON) and then load the data into the page with JavaScript.

use JavaScript (or a JS Framework, I prefer jQuery) and use Ajax-Methods to display the data.

Related

Buttons duplicating but action works

My code displays all data from my column workouts with the status "to_do" but it also duplicates the submit_abs button in the modal. This is what happens
Clicking a button updates the status correctly.
<?php # start of first php code
$id = $_GET['id'];
$sql = "SELECT * FROM workouts WHERE w_traineeid = '$id' AND w_status = 'to_do'";
$results = mysqli_query($conn, $sql);
$resultChecks = mysqli_num_rows($results);
if ($resultChecks > 0) {
while ($row = mysqli_fetch_assoc($results)) # end of first php code
{
?>
</span>
<?php
}
}
?>
The reason that there are multiple buttons is because you are creating them in a loop. Remove the while loop & you will only get one button:
<?php # start of first php code
$id = $_GET['id'];
$sql = "SELECT * FROM workouts WHERE w_traineeid = '$id' AND w_status = 'to_do'";
/*$sql = "SELECT * FROM workouts";*/
$results = mysqli_query($conn, $sql);
$resultChecks = mysqli_num_rows($results);
if ($resultChecks > 0) { # end of first php code
?>
</span>
<?php
}
?>
You are currently checking if the number of rows in $results is more than 0 & then adding a button for each row.

unable to delete record with php and ajax

I'm just trying to delete a record by its row id from a table using php and ajax but when I click on the button it neither shows error nor performs the action.
here is my delete.php code:
<?php
session_start();
include 'db.php';
if(isset($_GET['name'])){
$user = $_GET['name'];
$query = mysqli_query($con, "SELECT * FROM login WHERE username='$user'") or die (mysqli_error());
$result = mysqli_num_rows($query);
while($row = mysqli_fetch_array($query)){
$_SESSION['user'] = $row['username'];
}
}
$query = mysqli_query($con, "SELECT * FROM pm WHERE touser = '".$_SESSION['user']."' ORDER BY pmdate DESC" ) or die (mysqli_error());
$result = mysqli_num_rows($query);
while($row = mysqli_fetch_array($query)){
$id = $row['id'];
$delquery = mysqli_query($con, "DELETE * FROM pm WHERE id ='$id'") or die (mysqli_error());
$delresult = mysqli_num_rows($delquery);
}
?>
and here is the ajax and delete code of html
<script>
$("#delete").click(function() {
$.ajax({
type: "POST",
url: "delete.php",
success: function(response){
$("#messages").html(response);
}
});
});
</script>
<div id="messages"></div>
any one have any ideas?
Change you query
-> your "DELETE * FROM pm WHERE id ='$id'"
-> correct "DELETE FROM pm WHERE id ='$id'"
You send POST method true AJAX and in php code you write GET, change it.
you set -> type: "POST" and use a GET method in your link
you then use -> $user = $_GET['name'];
+ did you try to echo GET / POST vars before you query and echo your query ?
+ I guess you send nothing to your page...
+ don't use * in DELETE query
You have few issues in your code.
1. you are not sending any parameters to the delete.php page. Please send the record ID to the delete.php page
2. remove * from DELETE query
3. you are adding PHP variables in HTML anchor tag without using PHP tags. you need to correct the link
4. you need to add event.preventDefault() inside your function

obtaining comments for each post

hi I have to create a system of comments within various trhead I performed before and all the while the trhead 'while inside the comment and it works but is really slow and with a large number of threads often gives me timeout error how can I fix the problem?
function commenti($id) {
$query2 = "SELECT * FROM table2 WHERE numid='$id' ORDER BY id ASC";
$result2 = mysqli_query($conn,$query2);
if($result2->num_rows >0)
{
while($row2 = $result2->fetch_array(MYSQLI_ASSOC))
{
$idt2 = $row2['id'];
$testot2 = $row2['testo'];
return $testot2;
}
} else {
echo "No comment";
}
}
$query = "SELECT * FROM table1 where visualizza='1' ORDER BY id DESC";
$result = mysqli_query($conn,$query);
if($result->num_rows >0)
{
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$id = $row['id'];
$titolo = $row['titolo'];
$testo = commenti($id);
echo "$titolo $testo <br>";
}
}
mysqli_close($conn);
?>
I thought to use the join but if there are more duplicates also post comments
$query = "SELECT * FROM table1 left JOIN table2 ON table1.id = table2.numid where visualizza='1' ORDER BY id DESC";
I'm going to assume that you are trying to pull a ton of records. The best way to approach this is to add pagination and only load ~10-20 comments per page. depending on your server
Update:
#OP Basically on first load of the page you load ~10 comments, once they click view more then you load in the next few using ajax. Rinse and repeat.

Empty list of notifications

I am building a custom social network in php and mysqli. I have a page called notifications.php that shows the user site notifications as well as friend requests! put simply all I want to do is allow the user to purge his notifications list by clicking on a button!
in my html I have this...
<p><span id="purgeList"><?php echo $purgeList; ?></span></p>
<h2>Notifications</h2><?php echo $notification_list; ?></div>
and so far all I have for the button is this....
<?php
$purgeList = '<button disabled>Purge your List</button>';
if ($notification_list == true){
$purgeList = '';
}
?>
The notifications themselves gets pulled in using this script!
$notification_list = "";
$sql = "SELECT * FROM notifications WHERE username LIKE BINARY '$log_username' ORDER BY date_time DESC LIMIT 5";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows < 1){
$notification_list = "You do not have any notifications";
} else {
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$noteid = $row["id"];
$initiator = $row["initiator"];
$app = $row["app"];
$note = $row["note"];
$date_time = $row["date_time"];
$date_time = strftime("%b %d, %Y", strtotime($date_time));
$notification_list .= "<p><a href='user.php?u=$initiator'>$initiator</a> | $app<br />$note</p>";
}
}
mysqli_query($db_conx, "UPDATE users SET notescheck=now() WHERE username='$log_username' LIMIT 1");
If you are looking for a way to remove their notifications on the fly, you will need to do an XHR request (also known as AJAX)
for documentation on this you can visit jQuery API for more info on that.
you can cause them to reload the page to go to delete their notifications then use a header redirect to send them back to their 'news feed'
In my opinion i would use ajax because it does not cause a page reload and it can happen dynamically.
Hope this helps =)

Creating multiple pages from sql query

I am trying to create multiple pages from my query. If I have 100 results, and I want 10 results per page, I would like there to be ten pages created, with each page showing a different query. This is how my query is set up:
$sql ="SELECT * FROM Post WHERE (active ='1') ORDER BY PostID DESC ";
$result = mysql_query($sql,$db);
$numrows = mysql_num_rows($result);
while(($post = mysql_fetch_assoc($result))) {
$posts[] = $post;
}
<?php
if (!$numrows){ echo $errormessage;}
else{
foreach($posts as $post): ?>
echo stripslashes($post['text']);
<?php endforeach; }?>
This pulls each "post" from the database and puts displays them all out.
I would like to do something like this:
$results = mysql_num_rows($result);
$numpages = 10/$results; //gives the number of pages
while($numpages<$results)
{
//run code from above\\
}
What is the best way to do this with the method that I use? I appreciate your opinions because I'm at one of those stages where I'm lost in my own logic. Thank You!
Most pagination examples fail to meet real life requirements. A custom query string, for example.
So, here is a complete yet concise example:
<?
per_page=10;
// Let's put FROM and WHERE parts of the query into variable
$from_where="FROM Post WHERE active ='1'";
// and get total number of records
$sql = "SELECT count(*) ".$from_where;
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
$row = mysql_fetch_row($res);
$total_rows = $row[0];
//let's get page number from the query string
if (isset($_GET['page'])) $CUR_PAGE = intval($_GET['page']); else $CUR_PAGE=1;
//and calculate $start variable for the LIMIT clause
$start = abs(($CUR_PAGE-1)*$per_page);
//Let's query database for the actual data
$sql = "SELECT * $from_where ORDER BY PostID DESC LIMIT $start,$per_page";
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
// and fill an array
while ($row=mysql_fetch_array($res)) $DATA[++$start]=$row;
//now let's form new query string without page variable
$uri = strtok($_SERVER['REQUEST_URI'],"?")."?";
$tmpget = $_GET;
unset($tmpget['page']);
if ($tmpget) {
$uri .= http_build_query($tmpget)."&";
}
//now we're getting total pages number and fill an array of links
$num_pages=ceil($total_rows/$per_page);
for($i=1;$i<=$num_pages;$i++) $PAGES[$i]=$uri.'page='.$i;
//and, finally, starting output in the template.
?>
Found rows: <b><?=$total_rows?></b><br><br>
<? foreach ($DATA as $i => $row): ?>
<?=$i?>. <?=$row['title']?><br>
<? endforeach ?>
<br>
Pages:
<? foreach ($PAGES as $i => $link): ?>
<? if ($i == $CUR_PAGE): ?>
<b><?=$i?></b>
<? else: ?>
<?=$i?>
<? endif ?>
<? endforeach ?>
It would be hideous to extract all data from the database and manage it from PHP. It would kill the RAM, and the network.
Use the LIMIT clause for paging.
First, you need to see the total number of records. Use
$query = 'SELECT count(1) as cnt FROM Post WHERE active =1';
then,
$result = mysql_query($query, $db);
$row = mysql_fetch_assoc($result);
$count = $row['cnt'];
$pages = ceil($count/10.0); //used to display page links. It's the total number of pages.
$page = 3; //get it from somewhere else, it's the page number.
Then extract the data
$query = 'SELECT count(1) as cnt FROM Post WHERE active =1 LIMIT '.$page*10.', 10';
$result = mysql_query($query, $db);
while($row = mysql_fetch_assoc($result))
{
//display your row
}
Then output the data.
I'm using that similar code to do that:
$data = mysql_query("SELECT * FROM `table`");
$total_data = mysql_num_rows($data);
$step = 30;
$from = $_GET['p'];
$data = mysql_query("SELECT * FROM `table` LIMIT '.$from.','.$step.'"
That code get total rows
and that for creating links:
$p=1;
for ($j = 0 ; $j <= $total_data+$step; $j+=$step)
{
echo ' '.$p.' ';
$p++;
} ?>
You can also read about : pagination

Categories