select from database order by mysql php - php

I'm trying to ordonate some things in oder by date, but the query that should select the articles doesn't work. I have an issue with where and order by.
What i've tried:
$query = mysql_query("select * from my_article where id = '<?php echo $_SESSION['idArticle]';?>' order by date") ;
How can i fix this?

A Suggestion:-
Regarding mysql_*:-
Deprecated from php5.5 onward
Removed from php7.0.
So use mysqli_* or PDO(with prepared statements).
Current solution:-
<?php
$id = $_SESSION['idArticle']; // here `'` is missed in your question code
$query = mysql_query("select * from my_article where id = $id order by `date`") ;

$query = mysql_query("select * from my_article where id='".$_SESSION['idArticle']."' order by date") ;
You can try this. You need to think sql injection ;)

Make sure data type of date field is not varchar.

Related

Php : variable into SQL QUERY (PDO)

I'm calling a table from mySQL database using PDO as you can see :
$reponse = $bdd->query('SELECT * FROM exercices WHERE chapitre=\'hello\' ORDER BY id DESC');
Now, I want to do the same thing but instead of 'hello' I would like to use a variable set before like that :
$reponse = $bdd->query('SELECT * FROM exercices WHERE chapitre=\'echo $cat\' ORDER BY id DESC');
It doesn't work. I may have a problem with "echo $cat". Somebody knows ? Thanks.
Use binded variables, I don`t know where the variable is coming from but to be safe:
$reponse = $bdd->query('SELECT * FROM exercices WHERE chapitre=:cat ORDER BY id DESC');
$reponse->bindParam(':cat', $cat, PDO::PARAM_STR); //assuming it is a string
$reponse->execute();
$result = $reponse->fetchAll(); //make the select
print_r($result); //debug
your query can be:
$reponse = $bdd->query('SELECT * FROM exercices WHERE
chapitre=\''.$cat.'\' ORDER BY id DESC');
you should understand the difference between "" and '', also you can " in 2 single quota without any problem and vice versa. if you want write " in 2 double quota you should use \ also the same when you write ' in 2 single quota.
The way I do a query like that is this:
$cat = $_POST['cat'];
$response = $bdd->prepare("SELECT * FROM exercices WHERE chapitre= :cat ORDER BY id DESC");
$response->bindParam(':cat', $cat,PDO::PARAM_STR);
$response->execute();
I like this the best as it's clean and easy to understand.
You do not need to echo the variable when passing it as argument. Wrap the whole string in double quotes and place the variable.
Double quotes strings are parsed by PHP to place the variable values in string.
Use it in this way
$reponse = $bdd->query("SELECT * FROM exercices WHERE chapitre= '$cat' ORDER BY id DESC");

Pulling records between two dates from a VIEW

I have a mysql datetime field that stores dates in the form '2013-12-25 00:00:00'
I need to select all records for any month in the table with a query like:
$sql = "SELECT *
FROM `images`
WHERE (photodate BETWEEN '2003-11-01 00:00:00' AND '2003-12-03 00:00:00')
ORDER BY photodate DESC
LIMIT 30";
The above select query does the job fine.
In order to change the dates, I need to replace the '2003-11-01 00:00:00'AND'2003-12-03 00:00:00' with variables, so I set a variable with input data from two drop down lists for $startyear and $startmonth and convert it to what I think is the correct form using:
$startdate = $startyear."-".$startmonth."-01 00:00:00";
I do the same to the $enddate by adding 1 to the $startmonth.
My code then becomes:
$sql = "SELECT *
FROM `images`
WHERE (photodate BETWEEN $startdate AND $enddate)
ORDER BY photodate DESC
LIMIT 30";
This does not work at all and gives a MySQL error. Having struggled with it for a month and finding nothing on any forum that uses variables instead of text, I am totally at a loss as to how it could be done. All help appreciated.
You are vulnerable to SQL injection attacks, which is why it's not working. You're producing the literal query
... WHERE (photodate BETWEEN 2003-11-01 00:00:00 AND 2013-12-03 00:00:00)
The 2003-11-01 and 2013-12-03 will be interpreted as a series of mathematical subtractions, and the 00:00:00 will be a simple flat-out syntax error. You need to, at bare minimum, quote those values:
... WHERE (photodate BETWEEN '$startdate' AND '$enddate')
^----------^-----^--------^--- note the quotes
so that mysql can see the WHOLE date as a date value, and not some arbitrary broken strings.
I guess you're missing some apostrophes... try this:
$sql = "SELECT * FROM images WHERE (photodate BETWEEN '$startdate' AND '$enddate') ORDER BY photodate DESC LIMIT 30";
You could have problems with the logic. In $enddate doesn't adding 1 to the start month give you 13?
Try printing out the contents $sql when the variables are in and see how it compares to the working $sql.
Please add apostrophes your query (and sanitize your variables using mysql_real_escape_string, PDO bind values, mysqli_real_escape_string) :
$sql = 'SELECT * FROM 'images' WHERE (photodate BETWEEN '.$startdate.' AND '.$enddate.') ORDER BY photodate DESC LIMIT 30';
A little reminder, you shall NOT use MySQL (deprecated, old.. and not that fast), if you're using MySQLi or going to use it, please sanitize your variables like this, as Marc B said it could break your script and your app security :
<?php
// Starting MySQLi Connection
$db = mysqli_connect("host", "user", "password", "dbname");
// Sanitizing your variables
$startdate = mysqli_real_escape_string($db, $startdate);
$enddate = mysqli_real_escape_string($db, $enddate);
// Query
$sql = "SELECT * FROM 'images' WHERE (photodate BETWEEN ".$startdate." AND ".$enddate.") ORDER BY photodate DESC LIMIT 30";
// Doing the query and print the result array
$var = mysqli_query($db, $sql);
print_r($var);
// Closing connection
mysqli_close($db);
?>
Please refer to to this for PDO way or to this for MySQLi way, you can also check the MySQL_real_escape_string into PHP doc but MySQL functions are deprecated since PHP 5.5

mysql statement error .No result

Alright so right now i am generating a report from submit button and it has two input type that are from and to but the thing is i want from and too date and the result isnt showing up from the database
$order_time=$_POST["datefrom"];
$order_time=$_POST["dateto"];
$query = "SELECT * FROM ss_orders where order_time='".$order_time."' limit 60";
Thats my above code , so is it possible to use between in that above query ? and also my data type in the database of order_time is datetime ? so why i am not getting any result ?
Thanks in advance :) Help will be appreciated :)
$order_time=$_POST["datefrom"];
$s= date("Y-m-d", strtotime($order_time));
$order_timeto=$_POST["dateto"];
$e= date("Y-m-d", strtotime($order_timeto));
$query = "SELECT * FROM ss_orders where datetime<=$s and datetime>=$e";
as a programmer you should check and debug your code in all possible ways,you can print what are the values these variables having and you cal also print the query so you can know what is the actual query executing.
$fromdate=$_POST["datefrom"];
$todate=$_POST["dateto"];
$query = "SELECT * FROM ss_orders where datetime<='$todate' and datetime>='$fromdate' limit 60";
and PDO/MYsqli for security

Is this an efficient way to create a post stream, or is there a better way? [duplicate]

This question already has answers here:
PHP - Using PDO with IN clause array
(9 answers)
Closed 6 years ago.
$FSQL = $pdo->query('SELECT * FROM `connections` WHERE `uid`="'.$my_id.'" && `type`="1" ORDER by `id` DESC');
$myfriends = '`uid`="'.$my_id.'" ';
while($po = $FSQL->fetch(PDO::FETCH_ASSOC)){
$myfriends .= ' || `uid`="'.$po['cid'].'"';
}
$dsk = $pdo->query("SELECT * FROM `posts` WHERE ".$myfriends." ORDER by `id` DESC LIMIT ".$limitCount);
I have been trying to create a nice post stream, and I finally got my code down. But it seems so inefficient if you have a large amount of connections (connections being anything from friends, pages, or events).
Could someone tell me if there is a better way to do this?
--by the way: this is working perfectly already, but I feel like i'll run into issues down the line
$FSQL = $pdo->query('SELECT * FROMconnectionsWHEREuid="'.$my_id.'" &&type="1" ORDER byidDESC');
This is vulnerable to SQL Injection. You should be using parameters and prepared statements. See the Documentation.
Worked Example
$sql = $pdo->prepare('SELECT * FROM `table` WHERE `uid`=:uid');
// Create the SQL statement, with the parameter prefixed by a ":".
$userID = "username";
// Grab the value you wish to bind to your parameter.
$sql->bindParam(':uid', $userID);
// Bind the values, using the bindParam method.
$sql->execute();
// Execute the statement with the parameters bound to the SQL query.
You don't want to use a subquery?
Something like this...
$dsk = $pdo->query(
"SELECT *
FROM `posts`
WHERE uid IN (
SELECT cid
FROM `connections`
WHERE `uid`="'.$my_id.'" && `type`="1"
)
ORDER BY `id` DESC LIMIT " . $limitCount);
And try not to use * when you don't need all fields.

mysql like statement is not working as expected

I have a table with 4 record.
Records: 1) arup Sarma
2) Mitali Sarma
3) Nisha
4) haren Sarma
And I used the below SQL statement to get records from a search box.
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%$q' LIMIT 5";
But this retrieve all records from the table. Even if I type a non-existence word (eg.: hgasd or anything), it shows all the 4 record above. Where is the problem ? plz any advice..
This is my full code:
$q = ucwords(addslashes($_POST['q']));
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%".$q."' LIMIT 5";
$rsd = mysql_query($sql);
Your query is fine. Your problem is that $q does not have any value or you are appending the value incorrectly to your query, so you are effectively doing:
"SELECT id,name FROM ".user_table." WHERE name LIKE '%' LIMIT 5";
Use the following code to
A - Prevent SQL-injection
B - Prevent like with an empty $q
//$q = ucwords(addslashes($_POST['q']));
//Addslashes does not work to prevent SQL-injection!
$q = mysql_real_escape_string($_POST['q']);
if (isset($q)) {
$sql = "SELECT id,name FROM user_table WHERE name LIKE '%$q'
ORDER BY id DESC
LIMIT 5 OFFSET 0";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "id: ".htmlentities($row['id']);
echo "name: ".htmlentities($row['name']);
}
} else { //$q is empty, handle the error }
A few comments on the code.
If you are not using PDO, but mysql instead, only mysql_real_escape_string will protect you from SQL-injection, nothing else will.
Always surround any $vars you inject into the code with single ' quotes. If you don't the escaping will not work and syntax error will hit you.
You can test an var with isset to see if it's filled.
Why are you concatenating the tablename? Just put the name of the table in the string as usual.
If you only select a few rows, you really need an order by clause so the outcome will not be random, here I've order the newest id, assuming id is an auto_increment field, newer id's will represent newer users.
If you echo data from the database, you need to escape that using htmlentities to prevent XSS security holes.
In mysql, like operator use '$' regex to represent end of any string.. and '%' is for beginning.. so any string will fall under this regex, that's why it returms all records.
Please refer to http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html once. Hope, this will help you.

Categories