Load MySql table from bottom to top - PHP - php

Today is my first day ever messing with PHP or MySQL... I tried to make a simple chat program... it works great but it displays the old chats first and the newest chats (which are at the bottom of my table) last (at the bottom of the page).. how can I load the table in reverse order? So it displays the rows front he bottom of the database table at the top of my HTML table?
Here is my code... All in the file called "Chat.php"
<html><head></head><body>
<form action="chat.php" method="post">
Message: <br><textarea type="text" name="message" style="width:80%; height:300px;"></textarea><br>
<input type="submit" />
</form>
<?php
$host="****";
$user="****";
$password="****";
$cxn = mysql_pconnect ($host, $user, $password);
mysql_select_db("defaultdb", $cxn);
if (getenv(HTTP_X_FORWARDED_FOR)) {
$ipaddress = getenv(HTTP_X_FORWARDED_FOR);
} else {
$ipaddress = getenv(REMOTE_ADDR);
}
$message = $_POST["message"];
mysql_query("INSERT INTO ChatTest (ID, TimeStamp, Message) VALUES ('$ipaddress', NOW(), '$message')");
$data = mysql_query("SELECT * FROM ChatTest") or die(mysql_error());
Print "<table border cellpadding=3>";
Print "<tr>";
Print "<th>ID:</th><th>TimeStamp:</th><th>Message:</th>";
while($info = mysql_fetch_array( $data )) {
Print "<tr>";
Print " <td>".$info['ID'] . "</td> ";
Print " <td>".$info['TimeStamp'] . " </td>";
Print " <td>".$info['Message'] . "</td></tr>";
}
Print "</table>";
mysql_close($cxn);
?>
</body></html>

What you are looking for is MySQL's ORDER BY statement. You can use it to tell the DBMS in which order you want your results.
SELECT * FROM ChatTest
ORDER BY `TimeStamp` DESC
And just another thing…
I realize that this is your first attempt, so it's understandable that there'll be mistakes. One thing, however, you should learn about right away is SQL Injections.
Consider an example where the user's message is
0'); DROP TABLE ChatTest --
So suddenly your query would look like
INSERT INTO ChatTest (ID, TimeStamp, Message)
VALUES ('$ipaddress', NOW(), '0'); DROP TABLE ChatTest --')
To prevent this, always run user input through mysql_real_escape_string(), like this:
$message = mysql_real_escape_string($_POST['message']);

Explicitly specify your sort key:
$data = mysql_query("SELECT * FROM ChatTest ORDER BY PostDate DESC") or die(mysql_error());

Related

How to order rows from newest to oldest MySQL & PHP?

I made a comments section on my website using PHP & MySQL. However all the old comments are at the top and the new comments are at the bottom. How do I flip the order so new comments are on top and old ones are at the bottom?
Here's my comments.inc.php:
<?php
function setComments($conn) {
if (isset($_POST['commentSubmit'])) {
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid', '$date', '$message')";
$result = $conn->query($sql);
}
}
function getComments($conn) {
$sql = "SELECT * FROM comments";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo "<div class='comment-box'><p>";
echo $row['uid']."<br>";
echo $row['date']."<br>";
echo '<input type="button" value="More Info" onclick="window.location=\'more_info.php?start=' . urlencode($row['message']) . ' \';" />';
echo "</p></div>";
}
}
Thanks in advance! :)
Depending on the date and time we can show older once at the top and newer comments at the bottom:
SELECT * FROM comments ORDER BY date desc
SELECT * FROM comments ORDER BY date DESC
SELECT * FROM comments ORDER BY date DESC
For more info you can refer below link. All possibilities are listed.
https://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html
You could use ORDER BY date DESC or same with primary key field if it is autoincrement when building your query.

Display only the latest entry in Database and constantly checking for update after every 5 mins

I have a form constantly receiving input from users,
I need to keep displaying the next entry comment and only that comment.
I have id, Name and Comment in my database table 'demo'
id Name Comment
1 john hello
2 may yo
3 dereck all the best
How to display 1 entry only then after 5 mins, next entry and repeat?
Viewing.php:
<?php
//connection to
require 'config.php';
$conn = mysqli_connect( $db_host, $db_username, $db_password, $db_name);
// Create connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$sql = "SELECT * FROM `demo` ORDER BY `id` DESC ";
$sql = "SELECT id, Name, Comment FROM demo";
$result = $conn->query($sql);s
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table border='1'>";
echo "<tr><td height='150px'></td></tr>";
echo "<tr><td width='30%'> <td>";
echo "<td><div id='colcenter' style='background:url(viewBG.png);width:700px;height:650px;'>".$row["Comment"]."<br>From : ".$row["Name"]."</div></td>";
echo "<td width='30%'> <td>";
echo "<tr><td height='150px'></td></tr>";
echo "</table>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I think there is a better way.Use max():
SELECT Max(id) as MaxId FROM `DEMO`
Edit
first imagine it's your .html or your .php file that contains a button:
<script>
function Show(){
$.post("example.php",{method:'show'},function(data){
$("#entry").html(data)
});
}
</script>
<div id="entry">entries will be shown here</div>
<input type="button" value="Show me new entries" onClick="Show ();" />
and then in example.php you can echo the last entry.I think you know what you should write in example.php but let's give you a sample:
<?php
if(isset($_POST['method']) and trim($_POST['method'])==='show'){
//echo the last entries
}
?>
You could use the id, if it's autoincrement, to get the latest post. Do:
SELECT * FROM DEMO ORDER BY id DESC LIMIT 1
That will give you the entry with the greatest id (= the entry last inserted).

What is an SQL query for counting records that are existing more than once in a database?

<?php
mysql_connect("localhost", "root", "");
mysql_select_db("students");
$id = $_POST['id'];
$grade = $_POST['grade'];
$query = "INSERT INTO `st_table` (`St_id`,`Grade`) VALUES ('$id','$grade')";
$result = mysql_query($query);
$query = "SELECT * from `st_table`";
$result = mysql_query($query);
echo "<table>";
echo "<th>St_id</th><th>Grade</th>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['St_id'] . "</td><td>" . $row['Grade'] . "</td></tr>";
}
This code adds values into a table both ID and Grade. I want another query that will be able to count how many As, Bs, Cs, etc. and OUTPUT it on an html table.
Here, Your query is ok just group by Grade not Grades
"SELECT `Grade`, COUNT(*) AS count FROM `st_table` GROUP BY `Grade`";
Here is sqlfiddle
After edit
The query i am mentioning should work for you, you can check fiddle for that as for as you modified code is concerned you have to change your table a bit since you are going to include St_id as well so make it 3 column and correspondingly change query too.

Can't check which check list is checked

I'm trying to delete multiple pictures using checkbox item. But somehow pictures are not deleted from database.
the coderuns without mistake. Page is being redirected but the delete query is not executed.
I believe there is somethong to do with passing picture id to query $List[1] but i really can't understand what.It seems I'm doing everything ok.
Thanks for any help in advance.
That's the code:
<?php
$Connection = mysql_connect( $Host, $User, $Pass ) or die('ERROR: '.mysql_error());
mysql_select_db( $DataBase )or die('ERROR: '.mysql_error());
$Query = "SELECT * FROM pictures WHERE folder_id = ".$FolId.";";
$Picture = mysql_query($Query, $Connection)or die('ERROR: '.mysql_error());
?>
<form name='Photos' method='POST' >
<?php
while($List = mysql_fetch_array($Picture)){
echo "<input type='checkbox' name='photoList[]' value='".$List[1]."'> <span> ".$List[4]."</span>";
}
?>
<input type='submit' name='Delit' value='DELETE' >
</form>
<?php
if(isset($_POST['Delit'])){
foreach($_POST['photoList'] as $item){
$Query="DELETE FROM pictures WHERE picture_id =".$item;
mysql_query($Query, $Connection)or die("ERROR: ".mysql_error());
header('Location: photos.php');
}
}
?>
My guess is that $List[1] doesn't contain your picture_id. It's probably $List[0].
Using fetch_array is not a great way to get data from a DB using SELECT *, as your columns may change position, and an index doesn't clearly say which column you're retrieving.
Try using fetch_assoc instead, to get the column names associated with the data.
<?php
// Change `picture_name` below to the name of the column storing your picture's name
while ($List = mysql_fetch_assoc($Picture)) {
echo "<input type='checkbox' name='photoList[]' value='{$List['picture_id']}'> <span> {$List['picture_name']}</span>";
}
?>
Also, try this for your DELETE logic:
Checking if photoList is set (vs. Delit)
Looping through your photo list and casting the values to (int) to prevent SQL Injection
Concatenating the list of IDs into a comma-delimited list using implode
Doing a DELETE... WHERE IN query, providing the photo ID list - this is much faster than looping through and doing several DELETE... WHERE = statements
Code:
<?php
if (isset($_POST['photoList']) && !empty($_POST['photoList'])) {
$photoIds = array();
foreach ($_POST['photoList'] as $photoId) {
$photoIds[] = (int) $photoId;
}
$photoIds = implode(',', $photoIds);
$Query = "DELETE FROM pictures WHERE picture_id IN ({$photoIds})";
mysql_query($Query, $Connection)or die("ERROR: ".mysql_error());
header('Location: photos.php');
}
?>

An instructor retrieves the student who are enrolled in the course he/she teaches

I am building a simple website that helps students and instructors in universities.
I am facing a problem about the following query:
An instructor retrieves the students' IDs and names who are enrolled in the course he/she teaches.
I have the following tables, followed by their fields:
Enrollment (CourseCode - StudentID - Grade)
Studnet (ID - Name)
As you can see the only connector between the two tables is the student ID.
The code that I wrote is
<?
session_start();
$COCODE = $_SESSION['GlobalCode'];
$result11 = mysql_query("SELECT * FROM Enrollment WHERE CourseCode = '$COCODE' ") ;
$row11 = mysql_fetch_array($result11);
$StID = $row11['StudentID'];
$result22 = mysql_query("SELECT * FROM Student where StudentID= '$StID' ") ;
echo "<table border cellpadding=3>";
while($row123 = mysql_fetch_array($result22))
{
echo "<tr>";
echo "<td>".$row123['ID']."</td> ";
echo "<td>".$row123['Name']."</td> ";
echo "</tr>";
}
echo "</table>";
?>
What I am trying to do is to retrieve the course code from the Enrollment table and then retrieving the students names through the ID.
The problem is that I got the following message:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
I hope you can help me solving the problem.
Thanks
Have you tried to narrow down which of the queries is causing the problem? That would be your first step. Some other pointers:
you need to check that each SQL query is successful and returning a valid value before using it in the next query... otherwise that query will cause an error.
Try using: mysql_query ($your_query) or die ('Error: '.mysql_error ()); for each query for a more detailed error message. (for debugging only, not for production)
That error usually means there's something wrong with your query, or perhaps you are not connected to your database. If its the first problem, try changing your query to this:
$result11 = mysql_query("SELECT * FROM `Enrollment` WHERE `CourseCode` = '$COCODE' ");
Otherwise, check your database connection.
Finally, I solved it.
I did the following changes:
$result11 = mysql_query("SELECT * FROM Enrollment WHERE CourseCode = '$InstID' ") or die ('Error: '.mysql_error ());
echo "<table border cellpadding=3>";
while($row11 = mysql_fetch_array($result11))
{
$StID = $row11['StudentID'];
$result22 = mysql_query("SELECT * FROM Students where ID = '$StID' ") or die ('Error: '.mysql_error ());
while($row123 = mysql_fetch_array($result22))
{
echo "<tr>";
echo "<td>".$row123['ID']."</td> ";
echo "<td>".$row123['Name']."</td> ";
echo "</tr>";
}
}
echo "</table>";
mysql_close($con);
?>
Thanks

Categories