Display list by most recent item first - php

I have an old CMS and i need to edit the code so that it displays the most recent items first as apose to the oldest first. The code below is from the file that i beleive needs editing. Any help most appreciated...
<?
require("inc/config.php");
if ($cms->mrow['usrlvl'] < $cms->ulid) {
header("Location: " . $cms->folder . "/home");
exit();
}
if (isset($_GET['dm'])) {
if ($_GET['dm'] == "a") {
$cms->dmsg = $cms->mrow['singular_title'] . " Added Successfully";
} else if ($_GET['dm'] == "u") {
$cms->dmsg = $cms->mrow['singular_title'] . " Updated Successfully";
} else if ($_GET['dm'] == "d") {
$cms->dmsg = $cms->mrow['singular_title'] . " Deleted Successfully";
} else if ($_GET['dm'] == "bd") {
$cms->dmsg = $_GET['t'] . " "; if ($_GET['t'] > 1) { $cms->dmsg .= $cms->mrow['title']; } else { $cms->dmsg .= $cms->mrow['singular_title']; } $cms->dmsg .= " deleted Successfully";
}
}
require("inc/header.php");
echo "<h1>" . $cms->mrow['title'] . "</h1>";
// Add button
if ($cms->user['ulid'] <= $cms->mrow['usrlvladd'] && ($cms->mrow['allowadd'] || $cms->user['ulid'] == 1)) echo "<span>Add " . $cms->mrow['singular_title'] . "</span>";
// Bulk button
if ($cms->user['ulid'] <= $cms->mrow['usrlvladd'] && $cms->mrow['allowbulkadd']) echo "<span>Add Multiple " . $cms->mrow['title'] . "</span>";
if (!empty($cms->dmsg)) echo "\n<div id=\"dmsg\"><h3><span>" . $cms->dmsg . "</span></h3></div>";
// Set Order BY based on previously saved session or Module Default
if (isset($_SESSION['module' . $cms->mid]['orderby'])) {
$cms->orderby = $_SESSION['module' . $cms->mid]['orderby'];
} else if ($cms->mrow['orderby'] > 0) { // Get order based on field in module table (default)
$fres = mysql_query("SELECT name FROM `" . $cms->prefix . "field_" . $cms->tbl . " WHERE fid=" . $cms->mrow['orderby']);
$cms->orderby = mysql_result($fres,0);
} else if ($cms->mrow['allowposition']) { // Order by ID otherwise
$cms->orderby = "position";
} else { // Order by ID otherwise
$cms->orderby = $cms->idname;
}
// Set Order By Direction based on previously saved session or Module Default
if (!empty($_SESSION['module' . $cms->mid]['direction'])) { // Set Order By first based on session if set
$cms->direction = $_SESSION['module' . $cms->mid]['direction'];
} else { // Order by ID otherwise
$cms->direction = $cms->mrow['direction'];
}
// List Filter Bar
if ($cms->mrow['allowsearch'] == 1 || $cms->mrow['allownpp'] == 1) $cms->listSearch();
// Set Current page based on previously saved session
if (isset($_SESSION['module' . $cms->mid]['pg']) && is_numeric($_SESSION['module' . $cms->mid]['pg'])) {
$cms->pg = $_SESSION['module' . $cms->mid]['pg'];
} else {
$cms->pg = 1;
}
// Generate ajax request to load content into div
echo "<script type=\"text/javascript\">\n";
echo "$(document).ready(function(){\n";
if (isset($_GET['upid'])) { $upid = $_GET['upid']; } else { $upid = 0; } // Update Record ID
echo "
document.pg = " . $cms->pg . ";
document.order = '" . $cms->orderby . "';
document.direction = '" . $cms->direction . "';
showModuleList('" . $cms->mrow['tablename'] . "',document.pg,document.order,document.direction,false," . $upid . ");
});
</script>\n";
// Ajax target div
echo "<div id=\"list\"></div>";
require("inc/footer.php");
?>

Related

Why is my php script not showing all data from mysql? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a php script that should change the TeamSpeak group of specific users.
For getting a bit visual aspect I added a table, so I can see what for users should get the groups.
My whole php script:
<?php
date_default_timezone_set("Europe/Berlin");
require ("config.php");
require ("groups.php");
include ("datenbank.php");
require_once("libraries/TeamSpeak3/TeamSpeak3.php");
$ts3_VirtualServer = TeamSpeak3::factory("serverquery://" . $cfg["user"] . ":" . $cfg["pass"] . "#" . $cfg["host"] . ":" . $cfg["query"] . "/?server_port=9987");
$user_check_confirmed = "SELECT * FROM Users WHERE TSUUIDconfirmed = '1'";
$result = mysqli_query($db, $user_check_confirmed);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
if($row['MainSteamGroup'] == '1' || $row['vip'] == '1'){
echo '<table border="1">';
echo '<thead>';
echo '<tr class="table-head">';
echo '<th class="column1">Username</th>';
echo '<th class="column2">Rocket League</th>';
echo '<th class="column3">CS:GO</th>';
echo '<th class="column1">FACEIT</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while($fetch = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo '<td class="column1">' . $fetch['Username'] . '</td>';
echo '<td class="column2">' . $fetch['RLHighestRank'] . '</td>';
echo '<td class="column3">' . $fetch['CSGOMM'] . '</td>';
echo '<td class="column1">' . $fetch['FACEITLVL'] . '</td>';
echo "</tr>";
}
echo '</tbody>';
echo '</table>';
echo '<br><br><br>';
// Rocket League
if($row['RLHighestRank'] == 'none'){
} else {
if($row) {
if($row['RLHighestRank'] == $row['RLHighestRankSet']){
}
}
if($row) {
if($row['RLHighestRank'] !== $row['RLHighestRankSet'] && $row['RLHighestRankSet'] !== '0' && strpos($row['activeranks'], 'Rocket League') !== false){
try {
$client = $ts3_VirtualServer->clientFindDb($row['TeamSpeakUUID'], true);
if( $ts3_VirtualServer->serverGroupClientDel($rl[$row['RLHighestRankSet']], $client[0]));
if( $ts3_VirtualServer->serverGroupClientAdd($rl[$row['RLHighestRank']], $client[0]));
$sql = "UPDATE Users SET RLHighestRankSet='".$row['RLHighestRank']."' WHERE TeamSpeakUUID='".$row['TeamSpeakUUID']."'";
if ($db->query($sql) === TRUE) { }
} catch(Exception $e) {
echo "<br>" . $row['Username'] . " Fehler!<br/>ErrorID: <b>". $e->getCode() ."</b>; [RocketLeague1] Error Message: <b>". $e->getMessage() ."</b><br>;";
}
}
}
if($row) {
if($row['RLHighestRankSet'] == '0' && strpos($row['activeranks'], 'Rocket League') !== false ){
try {
$client = $ts3_VirtualServer->clientFindDb($row['TeamSpeakUUID'], true);
if( $ts3_VirtualServer->serverGroupClientAdd($rl[$row['RLHighestRank']], $client[0]));
$sql = "UPDATE Users SET RLHighestRankSet='".$row['RLHighestRank']."' WHERE TeamSpeakUUID='".$row['TeamSpeakUUID']."'";
if ($db->query($sql) === TRUE) { }
} catch(Exception $e) {
echo "<br>" . $row['Username'] . " Fehler!<br/>ErrorID: <b>". $e->getCode() ."</b>; [RocketLeague2] Error Message: <b>". $e->getMessage() ."</b><br>;";
}
}
}
}
}
}
For testing I set every user in the db as "vip". Overall I have 8 users, so all the users should get their rank.
If I open the php site now, I see 4 users in den table and the others are getting the rank updated, so why is my script not working how it should like?
I mean, every user have like the same database entry, the only things that differs are the names and their ranks...
The structure here is a little difficult to grasp. Can you show some example data?
You have a duplicate while loop which will likely cause an issue. I had a little cleanup which might be worth running:
<?php
date_default_timezone_set("Europe/Berlin");
require("config.php");
require("groups.php");
include("datenbank.php");
require_once("libraries/TeamSpeak3/TeamSpeak3.php");
$ts3_VirtualServer = TeamSpeak3::factory("serverquery://" . $cfg["user"] . ":" . $cfg["pass"] . "#" . $cfg["host"] . ":" . $cfg["query"] . "/?server_port=9987");
$user_check_confirmed = "SELECT * FROM Users WHERE TSUUIDconfirmed = '1'";
$result = mysqli_query($db, $user_check_confirmed);
if (mysqli_num_rows($result) > 0) {
echo '<table border="1">';
echo '<thead>';
echo '<tr class="table-head">';
echo '<th class="column1">Username</th>';
echo '<th class="column2">Rocket League</th>';
echo '<th class="column3">CS:GO</th>';
echo '<th class="column1">FACEIT</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo '<td class="column1">' . $fetch['Username'] . '</td>';
echo '<td class="column2">' . $fetch['RLHighestRank'] . '</td>';
echo '<td class="column3">' . $fetch['CSGOMM'] . '</td>';
echo '<td class="column1">' . $fetch['FACEITLVL'] . '</td>';
echo "</tr>";
}
echo '</tbody>';
echo '</table>';
echo '<br><br><br>';
// Rocket League
if (isset($row['RLHighestRank']) && $row['RLHighestRank'] != 'none') {
if ($row['RLHighestRank'] !== $row['RLHighestRankSet'] && $row['RLHighestRankSet'] !== '0' && strpos($row['activeranks'], 'Rocket League') !== false) {
try {
$client = $ts3_VirtualServer->clientFindDb($row['TeamSpeakUUID'], true);
if ($ts3_VirtualServer->serverGroupClientDel($rl[$row['RLHighestRankSet']], $client[0])) ;
if ($ts3_VirtualServer->serverGroupClientAdd($rl[$row['RLHighestRank']], $client[0])) ;
$sql = "UPDATE Users SET RLHighestRankSet='" . $row['RLHighestRank'] . "' WHERE TeamSpeakUUID='" . $row['TeamSpeakUUID'] . "'";
if ($db->query($sql) === true) {
}
}
catch (Exception $e) {
echo "<br>" . $row['Username'] . " Fehler!<br/>ErrorID: <b>" . $e->getCode() . "</b>; [RocketLeague1] Error Message: <b>" . $e->getMessage() . "</b><br>;";
}
}
if ($row['RLHighestRankSet'] == '0' && strpos($row['activeranks'], 'Rocket League') !== false) {
try {
$client = $ts3_VirtualServer->clientFindDb($row['TeamSpeakUUID'], true);
if ($ts3_VirtualServer->serverGroupClientAdd($rl[$row['RLHighestRank']], $client[0])) ;
$sql = "UPDATE Users SET RLHighestRankSet='" . $row['RLHighestRank'] . "' WHERE TeamSpeakUUID='" . $row['TeamSpeakUUID'] . "'";
if ($db->query($sql) === true) {
}
}
catch (Exception $e) {
echo "<br>" . $row['Username'] . " Fehler!<br/>ErrorID: <b>" . $e->getCode() . "</b>; [RocketLeague2] Error Message: <b>" . $e->getMessage() . "</b><br>;";
}
}
}
}
That said, the conditions on this line in particular look quite complicated:
if ($row['RLHighestRank'] !== $row['RLHighestRankSet'] && $row['RLHighestRankSet'] !== '0' && strpos($row['activeranks'], 'Rocket League') !== false) {
Seeing the accompanying data with anything sensitive removed will help further.

Undefined index error in php (dropdown filters do not work)

Hey I searched a lot about this problem but everything I tried did not work. :(
My code has 3 dropdowns and they should work like search-filters but every time I select an option from the dropdown i get the undified index error for 3 lines & if I change another dropdown the other two filters get ignored... :(
This only the code for the first dropdown:
<?php
//when the filter changes, this php is called
$output = '';
if(isset($_POST["businessUnit"]))
{
if($_POST["businessUnit"] != '')
{
if($_POST["productGroup"] != '') //first undefined index
{
$sql = "SELECT * FROM item WHERE businessUnit = '".$_POST["businessUnit"]."' and productGroup = '".$_POST["productGroup"]."'";
}
else if($_POST["deviceType"] != '') //second undefined index
{
$sql = "SELECT * FROM item WHERE businessUnit =
'".$_POST["businessUnit"]."' and productGroup = '".$_POST["deviceType"]."'";
}
else if($_POST["productGroup"] != '' && $_POST["deviceType"] != '') //third undefined index error
{
$sql = "SELECT * FROM item WHERE businessUnit = '".$_POST["businessUnit"]."' and productGroup = '".$_POST["productGroup"]."' and deviceType = '".$_POST["deviceType"]."'";
}
else
{
$sql = "SELECT * FROM item WHERE businessUnit = '".$_POST["businessUnit"]."'";
}
}
else
{
$sql = "SELECT * FROM item";
}
$result = sqlsrv_query($connect, $sql);
while($row = sqlsrv_fetch_array($result))
{
$output .= "<tr><td>".
$row['businessUnit']."</td><td>".
$row['productGroup']."</td><td>".
$row['deviceType']."</td><td>".
$row['serialNumber']."</td><td>".
$row['location']."</td><td>".
$row['condition']."</td><td>".
$row['itemDescription']."</td><td>
<input type='checkbox'></input></td></tr>";
}
echo $output;
}
else{
$_POST["businessUnit"] = "";
}
?>
to handle undefined index error, $array[$key] != "" won't work, you have to use isset() first before not equal to blank check.
See the solution below, it may works.
if (isset($_POST["businessUnit"]))
{
if ($_POST["businessUnit"] != '')
{
if (isset($_POST["productGroup"]) && $_POST["productGroup"] != '') //first undefined index
{
$sql = "SELECT * FROM item WHERE businessUnit = '" . $_POST["businessUnit"] . "' and productGroup = '" . $_POST["productGroup"] . "'";
} else if (isset($_POST["deviceType"]) && $_POST["deviceType"] != '') //second undefined index
{
$sql = "SELECT * FROM item WHERE businessUnit =
'" . $_POST["businessUnit"] . "' and productGroup = '" . $_POST["deviceType"] . "'";
} else if (isset($_POST["productGroup"]) && $_POST["productGroup"] != '' && isset($_POST["deviceType"]) && $_POST["deviceType"] != '') //third undefined index error
{
$sql = "SELECT * FROM item WHERE businessUnit = '" . $_POST["businessUnit"] . "' and productGroup = '" . $_POST["productGroup"] . "' and deviceType = '" . $_POST["deviceType"] . "'";
} else
{
$sql = "SELECT * FROM item WHERE businessUnit = '" . $_POST["businessUnit"] . "'";
}
} else
{
$sql = "SELECT * FROM item";
}
$result = sqlsrv_query($connect, $sql);
while ($row = sqlsrv_fetch_array($result))
{
$output .= "<tr><td>" .
$row['businessUnit'] . "</td><td>" .
$row['productGroup'] . "</td><td>" .
$row['deviceType'] . "</td><td>" .
$row['serialNumber'] . "</td><td>" .
$row['location'] . "</td><td>" .
$row['condition'] . "</td><td>" .
$row['itemDescription'] . "</td><td>
<input type='checkbox'></input></td></tr>";
}
echo $output;
} else
{
$_POST["businessUnit"] = "";
}
}
I didn't get what you are trying to do. Please post show snapshot and specify clearly what you are trying to do. You can write:
echo "<pre>";print_r($_POST);
after $output = '';
and see what is there in the $_POST variable and yes if you don't found:
$_POST["productGroup"]
in the $_POST you will get undefined index. So make sure you are passing it in the $_POST request.

php get id to delete record

PHP beginner on line:).
I have two files (viewKands.php-listing records and izbrisi.php-for deleting records from database. I try to delete record from db(upisi). But no luck.
Here is the code...Where is my mistake?
viewKands.php:
$kon = mysqli_connect("localhost", "root", "", "upisi");
$kon->set_charset("utf8");
if (mysqli_connect_error()) {
echo "Greska pri konekcija so baza: " . mysql_error();
}
$sqlView = "SELECT idPrijava,brPrijava,jazik,struka,profil,imeKand,tatIme,"
. "prezKand from tblprijava ";
$result = mysqli_query($kon, $sqlView);
$rBr = 1;
while ($rowV = $result->fetch_assoc()) {
$id = $rowV["idPrijava"];
echo "<tr><td>" . $rBr . "</td><td>" . $rowV["brPrijava"] . "</td><td>" . $rowV["jazik"] . "</td><td>" . $rowV["struka"] .
"</td><td>" . $rowV["profil"] . "</td><td>" . $rowV["imeKand"] . " " . $rowV["tatIme"] . " " . $rowV["prezKand"] .
"</td><td><a href='uredi.php'>Уреди</a></td>" . " <td><a href='izbrisi.php?id=$id'>X</a></td>" . "</td></tr>";
$rBr++;
}
And izbrisi.php (for deleting records)
$delkon = mysqli_connect("localhost", "root","","upisi");
$delkon->set_charset("utf8");
if (isset($_GET["idPrijava"]) != "") {
$delete = $_GET["idPrijava"];
$dqry = "DELETE FROM tblprijava WHERE idPrijava='$delete'";
$delete = mysqli_query($delkon, $dqry);
if ($delkon->query($dqry) === TRUE) {
header("Location:viewKands.php");
} else {
echo mysqli_error($delete);
}
} else {
echo "ID error";
}
$delkon->close();
Change code to izbrisi.php
$delkon = mysqli_connect("localhost", "root","","upisi");
$delkon->set_charset("utf8");
if (isset($_GET["id"]) != "") {
$delete = $_GET["id"];
$dqry = "DELETE FROM tblprijava WHERE idPrijava='$delete'";
$delete = mysqli_query($delkon, $dqry);
if ($delkon->query($dqry) === TRUE) {
header("Location:viewKands.php");
} else {
echo mysqli_error($delete);
}
} else {
echo "ID error";
}
$delkon->close();

Positioning else condition in php

I have found this little piece of php codes that suites my requirements.
<?php
$allDocs = mysql_query("SELECT id, parent FROM modx_site_content ORDER BY id DESC");
while($doc = mysql_fetch_assoc($allDocs)) {
$parent = mysql_query("SELECT id FROM modx_site_content WHERE parent = " . $doc['id'] . " AND id = " . $doc['parent']);
if(mysql_num_rows($parent)) {
while($parentDoc = mysql_fetch_assoc($parent)) {
echo 'Infinte loop found<br /><br />';
echo 'Document #' . $doc['id'] . ' and document #' . $parentDoc['id'] . ' are each others parent.';
}
}
}
?>
I tried putting the else condition like this:
<?php
$allDocs = mysql_query("SELECT id, parent FROM modx_site_content ORDER BY id DESC");
while($doc = mysql_fetch_assoc($allDocs)) {
$parent = mysql_query("SELECT id FROM modx_site_content WHERE parent = " . $doc['id'] . " AND id = " . $doc['parent']);
if(mysql_num_rows($parent)) {
while($parentDoc = mysql_fetch_assoc($parent)) {
echo 'Infinte loop found<br /><br />';
echo 'Document #' . $doc['id'] . ' and document #' . $parentDoc['id'] . ' are each others parent.';
}
}
else {
echo 'No loop found';
}
}
?>
But it goes into the while loop. Where is the appropriate place to put the else condition?
Indenting was the solution:
<?php
$allDocs = mysql_query("SELECT id, parent FROM modx_site_content ORDER BY id DESC");
while($doc = mysql_fetch_assoc($allDocs)) {
$parent = mysql_query("SELECT id FROM modx_site_content WHERE parent = " . $doc['id'] . " AND id = " . $doc['parent']);
if(mysql_num_rows($parent)) {
while($parentDoc = mysql_fetch_assoc($parent)) {
echo 'Infinte loop found<br /><br />';
echo 'Document #' . $doc['id'] . ' and document #' . $parentDoc['id'] . ' are each others parent.';
}
} else {
//Your Code Here
break;
}
}
?>
The else of the if is inside the first loop but not the second.
Edit:Added the Break to Exit Loop.
Please intent your codeexample before submitting your question. Easeier to read...
It seems like the else-statement is placed correct. Look at your while-statements. Maybe the code never reaches the if-else statement because the first while-loop quits before the if-statemnt gets false. Or as long as the first while-loop runs, you'll always get a row with the the statement
$parent = mysql_query("SELECT id FROM modx_site_content WHERE parent = " . $doc['id'] . " AND id = " . $doc['parent']);

IF statement within WHILE not working

I am working on a basic messaging system. This is to get all the messages and to make the row of the table that has an unread message Green. In the table, there is a column called 'msgread'. this is set to '0' by default. Therefore it should make any row with the msgread = 0 -> green. this is only working for the first row of the table with the code i have - i verified that it is always getting a 0 value, however it only works the first time through in the while statement ..
require('./connect.php');
$getmessages = "SELECT * FROM messages WHERE toperson = '" . $userid . "'";
echo $getmessages;
$messages = mysql_query($getmessages);
if(mysql_num_rows($messages) != 0) {
$table = "<table><tr><th>From</th><th>Subject</th><th>Message</th></tr>";
while($results = mysql_fetch_array($messages)) {
if(strlen($results[message]) < 30){
$message = $results[message];
}
else {
$message = substr($results[message], 0 ,30) . "...";
}
if($results[msgread] == 0){
$table .= "<tr style='background:#9CFFB6'>";
$table .= "<td>" . $results[from] . "</td><td>" . $results[subject] . "</td><td><a href='viewmessage.php?id=" . $results[message_id] ."'>" . $message . "</a></td></tr>";
}
else {
$table .= "<tr>";
$table .= "<td>" . $results[from] . "</td><td>" . $results[subject] . "</td><td><a href='viewmessage.php?id=" . $results[message_id] ."'>" . $message . "</a></td></tr>";
}
}
echo $table ."</table>";
}
else {
echo "No Messages Found";
}
There's all the code, including grabbing the info from the database. Thanks.
if(strlen($results[message]) < 30){
the message probably should be quoted:
if(strlen($results['message']) < 30){
There are quite a few other similar issues
i tested your code an the only mistake i found was the lack of quoatation marks in the indices array $results. You are using this $result[message_id] when the most appropriate would be $result['message_id']. The rest works as expected, the records with msgread equal to 0 stayed with the green line.
Your code looks a little nasty and is not easy to read.
You should use mysqli_fetch_assoc().
Always end style with a ;
use quotation on associative array
more logic choice of var names
where does $userid come from? is the content safe?
Here is quickly cleaned version of your code :
$query = "SELECT * FROM messages WHERE toperson = '" . $userid . "'";
if($results = mysqli_query($query)) {
if(mysqli_num_rows($results) != 0) {
$table = "<table><tr><th>From</th><th>Subject</th><th>Message</th></tr>";
while($data = mysqli_fetch_assoc($results)) {
if(strlen($data['message']) > 30){
$data['message'] = substr($data['message'], 0 ,30) . "...";
}
$table .= "<tr";
if($data['msgread'] == 0){
$table .= " style='background:#9CFFB6;'";
}
$table .= ">";
$table .= "<td>" . $data['from'] . "</td><td>" . $data['subject'] . "</td><td><a href='viewmessage.php?id=" . $data['message_id'] ."'>" . $data['message'] . "</a></td></tr>";
}
echo $table ."</table>";
} else {
echo "No Messages Found";
}
}

Categories