Why is ORDER BY id DESC not working in this line? - php

I'm trying to get ORDER BY id DESC to work in this line of php but I can't get it to work. It works without it though but they just display in the opposite order. Where should I position it?
$query = mysql_query("SELECT * FROM photos ORDER BY id DESC WHERE title LIKE '%".$search."%'");
Update:
I've updated the php with your suggestion that works now thanks. I've also updated it to mysqli as suggested, could this be structured better in anyway? It is working, just wondered if anyone has any improvements?
<?php
$search = $_GET['search'];
$db = mysqli_connect("", "", "", "") or die ("could not connect to mysql");
$sql = "SELECT * FROM photos WHERE title LIKE '%".$search."%' ORDER BY id DESC";
$result = mysqli_query($db, $sql);
if(mysqli_num_rows($result) >=1) {
while ($row = mysqli_fetch_array($result)) {
echo"<div id='img_div'>";
echo"<img src='images/".$row['image']."'>";
echo"<h1>".$row['title']."</h1>";
echo"<p>".$date = date('j F, Y', strtotime($row['date']))."</p>";
echo"<p>".$row['link']."</p>";
echo"</div>";
}
//continue
}else{
echo "No Results";
}
?>

Your query is wrong. ORDER BY id DESC should be placed after the WHERE clause, like this:
$query = mysql_query("SELECT * FROM photos WHERE title LIKE '%".$search."%' ORDER BY id DESC");
Sidenote(s):
Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.
Learn about prepared statement because right now your query is susceptible to SQL injection attacks. Here's a good read on how you can prevent SQL injection in PHP.

Related

PHP mySQL Sort post by date

I'm trying to create a website where anyone can post anything to it without creating an account, long as its just text. My problem is because every time I start the website and post something. Its sent to the bottom, where oldest posts are at the top and new posts are sent to the top. I want to see the new posts on top instead. This is my first time working with PHP, mySQL and databases in general so my code might look bad. Tell me if more information / code is needed. Thank you for your time.
<?php
function setPosts($conn){
if(isset($_POST['postSubmit'])){
$pid = $_POST['pid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql= "INSERT INTO post(pid, date ,message) VALUES ('$pid', '$date', '$message');";
$result = mysqli_query($conn, $sql);
}
}
function getPosts($conn){
$sql = "SELECT * FROM post";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()){
echo "<div class='post-box'>";
echo $row['date']."<br>";
echo nl2br($row['message'])."<br><br>";
echo "</div>";
}
}
You need to add "ORDER BY" to your "SELECT" to sort it.
$sql = "SELECT * FROM post ORDER BY date DESC";
The "DESC" is there so that new posts will be on top. We'd use "ASC" if we wanted older posts on top.
You need to use ODRER BY clause like below :-
$sql = "SELECT * FROM post ORDER BY date DESC";
Reference:- ODRER BY clause
Note:- Your insersion code is wide open for SQL Injection. Use mysqli prepared statements to prevent from it.
Reference:- mysqli::prepare
You need to sort mysql result by date and order it in descending order.replace mysql query to this
$sql = "SELECT * FROM post SORT BY date order BY DESC";
function getPosts($conn){
$sql = "SELECT date,message FROM post ORDER BY date DESC";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()){
echo "<div class='post-box'>";
echo $row['date']."<br>";
echo nl2br($row['message'])."<br><br>";
echo "</div>";
}
}

PHP Script Not erroring and not running

My code is this:
<?php
echo "Test1";
$con=mysqli_connect("Removed");
$Amount=$_GET["Amount"];
$GetType=$_GET["Type"];
var_dump($GetType);
var_dump($Amount);
$sql_query = "SELECT * FROM EventRecord WHERE EventType='$GetType' ORDER BY EventId DESC";
$sql_result = mysqli_query($con,$sql_query)
or exit(mysqli_error($con));
while($sql_row = mysqli_fetch_assoc($sql_result)){
echo $sql_row['EventId'].'<br>';
}
mysqli_close($con);
?>
For some reason, when I go to http://www.example.com/MyPhp.php?Type=Join&Amount=10, all that is outputted is "Test1string(4) string(2)".
Note: I am aware of SQL Injection vulnerabilities, however they do not affect me specifically with this code. All table structure is correct.
Additionally, how would I make it echo the top rows, as determined by how large the EventId is, but echo only the top 2, or top 3, or top 7, or top any other number, depending on what $Amount is?
Replace
$sql_result = mysqli_query($con,$sql_query)
or exit(mysqli_error($con));
With
if(!($sql_result = mysqli_query($con,$sql_query))) {
exit(mysqli_error($con));
}
See :
PHP: mysqli::$error - Manual
and PHP: mysqli::query - Manual
How about using the LIMIT to display the first $Amount results from the database?
SELECT * FROM EventRecord WHERE EventType='$GetType' ORDER BY EventId DESC LIMIT 0, $Amount
Please correct me if I your question.

How to display table data in reverse? (php)

I have simple code for displaying images. I created table with 4 columns (ID, location, capture, equence) and inserted there 18 records. My question is: how to display all records from table in reverse mode? I need to make that the last entry will be displayed first, and the first entry displayed last.
What I need: 18-1
What I have now: 1-18
I was searching for simple codes to do that, but notwing worked at all. So i'd be very grateful if someone will help me to solve that problem.
Heres the basic code of my display script:
<?php
mysql_connect("localhost", "***", "***") or die(mysql_error());
mysql_select_db("martinidb1337") or die(mysql_error());
$result = mysql_query("SELECT * FROM klpgalerija") or die(mysql_error()); while($row = mysql_fetch_array( $result )) {
echo '<p><img src="'.$row['location'].'"></p>';
}
You have to use MySQL ORDER BY clause for that,
SELECT * FROM klpgalerija ORDER BY id DESC
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated.
So use either PDO or MySQLi (IMO PDO is way to go)
Changed query from "SELECT * FROM klpgalerija" to "SELECT * FROM klpgalerija ORDER BY ID DESC"
<?php
mysql_connect("localhost", "***", "***") or die(mysql_error());
mysql_select_db("martinidb1337") or die(mysql_error());
$result = mysql_query("SELECT * FROM klpgalerija ORDER BY ID DESC") or die(mysql_error()); while($row = mysql_fetch_array( $result )) {
echo '<p><img src="'.$row['location'].'"></p>';
}
add an order by desc clause in your sql query
$result = mysql_query("SELECT klpgalerija.* FROM klpgalerija order by klpgalerija.ID desc") or die(mysql_error());

mysql query fails if name has more then 1 words

I began to create a website for my small real estate business.
I played a bit with functions http://www.php.net mysql and I managed to make a page accessed via AJAX and returning html content for the search engine.
I have a database already populated with apartments and houses
The problem is that if the apartment name is "apartment" I return html content if "apartment with 3 rooms" it no longer write anything.
I do not understand where I was wrong:
<?php
$search = $_GET['selected'];
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('houses', $link);
function searchHouse($search, $link){
$query = "select * from houses where name=$search limit 1";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$query2 = "select * from houses_info where house_id=$row[id]";
$result2 = mysql_query($query2);
$row = mysql_fetch_assoc($result2);
return $row;
}
$result = searchHouse($search, $link);
echo $result['house_sq'];
echo "<br>";
echo $result['house_rooms'];
echo "<br>";
echo $result['house_bathrooms'];
echo "<br>";
echo $result['house_address'];
?>
you should know if you "played" with php.net that mysql_* functions are deprecated and are no longer maintained. It's a red box on top of the page informing you that.
you have a big MySQL injection hole there, you are not escaping $string at all
your problem is that you are not adding quotes to $string like: '$string'
you should stat using PDO to get rid of the bad code and SQL Injections holes.
you can wrap those 2 selects into a single select:
<?php
function searchHouse($search, $link){
$search = mysql_real_escape_string($search);
$query = "select * from houses_info where house_id IN (select * from houses where name='".$search."' limit 1)";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
return $row;
}
?>
since you are already building that website you can start moving to PDO, read this tutorial, your code will be more like this:
<?php
$db = new PDO('mysql:host=localhost;dbname=houses;charset=UTF-8', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$search = $_GET['selected'];
function searchHouse($search){
global $db;
$query = $db->prepare("select * from houses_info where house_id IN (select * from houses where name=:search limit 1)");
$query->execute(array(':search' => $search));
$row = $query->fetch(PDO::FETCH_ASSOC);
return $row;
}
$result = searchHouse($search);
?>
try:
$query = "select * from houses where name='".mysql_real_escape_string($search)."' limit 1";
and remember to always sanitize user input before passing it to sql to avoid sql injections.
Your first query should be:
$query = "select * from houses where name like $search% limit 1";
Strings need to be quoted in queries. Also, this is vulnerable to MySQL injection, make sure to escape $search with mysql_real_escape_string. Or even better yet use MySQLi or PDO instead of the old mysql_ functions.
$query = "select * from houses where name=$search limit 1";
Should be:
$query = "select * from houses where name='$search' limit 1";
Although you REALLY need to escape $search because it came from a user, even if they aren't malicious, any search queries with a single quote in it will break;
$search = $_GET['selected'];
Should be:
$search = mysql_real_escape_string($_GET['selected']);
(Anybody have the copy paste handy with the links to tutorials for MySQLi/PDO and such?)

Redefine Row Name

Is it possible to redefine a rows name when I use SELECT in MySQL?
"SELECT posts.id AS the_post_id FROM posts"
So I can call it from PHP as:
$query = mysql_query("SELECT posts.id AS the_post_id FROM posts");
while($row = mysql_fetch_array($query)){
// I call the ID with `the_post_id` and not `id`
echo $row["the_post_id"];
}
Yes, you have already done it correctly. Are you having issues with that?
Edit:
$query = mysql_query("SELECT posts.id AS the_post_id FROM posts") or die(mysql_error());
Try it like that and it would tell you if there is any issue with the query itself. Also i would suggest you look at the newer mysqli_* functions, mysql_* functions are history.

Categories