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");
Related
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.
This has been bugging for a long time, and I still can't figure out what i'm doing wrong.
In the code I want to select a few users with a comma separated string. The string will always be legit and valid.
In the first example, the one I would like to use, uses bindParam to assign the value of $postId to the SQL query. I have been using bindParam() for lots of other calls, but in this specific case, it fails.
$postId = "1,2,3";
$stm = $this->db->prepare('SELECT * FROM posts WHERE find_in_set(userId, "?") ORDER BY id DESC');
$stm->bindParam(1, $postId, PDO::PARAM_STR);
$stm->setFetchMode(PDO::FETCH_ASSOC);
$stm->execute();
$results = $stm->fetchAll();
return print_r($results,true);
This code returns:
array (
)
In this other code which I really wouldn't like to use, I just pass the value of $postId right into the sql query.
$stm = $this->db->prepare('SELECT * FROM posts WHERE find_in_set(userId, "'.$postId.'") ORDER BY id DESC');
$stm->setFetchMode(PDO::FETCH_ASSOC);
$stm->execute();
$results = $stm->fetchAll();
return print_r($results,true);
This code returns all the rows it is supposed to retrieve.
My question is; What is the specific problem and how can I avoid doing this again?
You shouldn't have quotes around the placeholder in yout query:
$stm = $this->db->prepare('SELECT * FROM posts WHERE find_in_set(userId, ?) ORDER BY id DESC');
See additional docs here.
Although it's not directly related to the question, it's also a handy habit to get into to use named params. When you have only one param to pass, it's not too bad, but when you start getting five or so question marks in the query, it's MUCH easier to actually read if you used named params:
SELECT * FROM posts WHERE find_in_set(userId, :someID) ORDER BY id DESC
Then you bind them as named params in your code:
$sth->bindParam(':someID', $postId, PDO::PARAM_STR);
You don't need to add the double quotes "?" when referencing the value
'SELECT * FROM posts WHERE find_in_set(userId, "?") ORDER BY id DESC'
Should be
'SELECT * FROM posts WHERE find_in_set(userId, ?) ORDER BY id DESC'
For the user I am testing with, their org_id column value is "student_life"
I am trying to have this function display whatever rows have the student_life column = 1. (so yes there is a column student_life which is a boolean, and then I also have a separate column named org_id and in this case has the value student_life)
I am pretty sure there is a syntax error but I cannot figure it out.
function org_id_users_table()
{
$org_id = mysql_real_escape_string($_POST["org_id"]);
$sql = $this->query("SELECT * FROM ".DBTBLE." WHERE '$org_id' = '1'");
$result = $sql['sql'];
$num_rows = $sql['num_rows'];
$this->create_table($result, $num_rows);
}
(when I replace $org_id in the "$sql=..." line with student_life the code works.
You're quoting the column name, which makes MySQL think it's a string.
$sql = $this->query("SELECT * FROM ".DBTBLE." WHERE $org_id = '1'");
Edit:
Based on your comments, I think what you actually want is this:
$sql = $this->query("SELECT * FROM ".DBTBLE." WHERE org_id = '$org_id'");
Change quotes.
$sql = $this->query("SELECT * FROM ".DBTBLE." WHERE `$org_id` = '1'");
P.S. Why shouldn't I use mysql_* functions in PHP?
Where is this coming from? $_POST["org_id"]
Do you have a form on the page posting that? Or are you just trying to get that from the database? If so, wouldn't you need another query to obtain that first?
$row_MyFirstQuery['org_id']
Otherwise if it is $_POST["org_id"], wouldn't it be single quotes not double? $_POST['org_id']
I can't figure out why sorting will work as long as I'm not using $sort as a passed in parameter. Example below will work for sorting:
$sort = "quantity desc";
$sql = " with items as (
SELECT i.[item_id]
,i.[name]
,i.[value]
,i.[quantity]
,i.[available]
,isnull(r.awarded, 0) as awarded
, ROW_NUMBER() OVER(
ORDER BY $sort
) rowNumber
FROM [Intranet].[dbo].[Goodwell_Item] i
LEFT JOIN (
SELECT r.item_id
, COUNT(1) awarded
from [Intranet].[dbo].[Goodwell_Reward] r
group by r.item_id
) as r
ON i.item_id = r.item_id
)
SELECT *
FROM items
WHERE rowNumber BETWEEN (?) and (?)
and ( (?) = '' OR (available = (?)))
";
$params = array( $pagify['startFrom'], $end, $available, $available );
$stmt = sqlsrv_query( $conn, $sql, $params );
However if I change the line with ORDER BY to:
ORDER BY (?)
and add it to my $params like so:
$params = array($sort, $pagify['startFrom'], $end, $available, $available );
then the sort for some reason is being ignored.
Please tell me how to get the sort working in a way that doesn't allow SQL injection.
I am dealing with this exact issue right now, and cannot find anything online to help.
I have tried:
$query = "SELECT * FROM {$this->view} WHERE SeriesID = ? ORDER BY ? ";
$result = $conn->getData($query, array($seriesID,$sortBy));
and
$query = "SELECT * FROM {$this->view} WHERE SeriesID = ? ORDER BY ? ?";
$result = $conn->getData($query, array($seriesID,$sortBy,$sortOrder));
In both cases, I get no error, and no results.
I think the only way to solve this safely is to use a switch statement before the query to manually validate the acceptable values. However, unless you're only ever dealing with one table, you can't know what the possible values are for the SortBy column.
However, if you just go with the assumption that the values at this point have already been cleaned, you can go with the non-parameterized version like this:
$query = "SELECT * FROM {$this->view} WHERE SeriesID = ? ORDER BY " . $sortBy . " " . $sortOrder;
$result = $conn->getData($query, array($seriesID));
What I plan to do is make sure to validate sortBy and sortOrder before I pass them to the method that contains this code. By doing it this way, each place I call the code becomes responsible for validating the data before sending it. The calling code would know the valid possible values for the table (or view in this case) that it is calling. (I'm the author of both pieces of code in this case, so I know it's safe.)
So, in short, just make sure that the values at this point in the code are already cleaned and safe, and push that responsibility up one level the code that calls this code.
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.