Set PHP variable to MySQL wildcard '%' [duplicate] - php

This question already has answers here:
pdo prepared statements with wildcards
(2 answers)
Closed 5 years ago.
I'm trying to query posts using PDO where the database column 'tags' = something.
My problem is: I want my query to work even if there's no $_GET['tag'] request is set and here's my code.
if (!isset($_GET['tag'])) {
$tags = '%';
} else {
$tags = $_GET['tag'];
}
$get_recipes = $con->prepare ("SELECT * FROM recipes WHERE tags = ?");
$get_recipes->execute(array($tags));
$recipes = $get_recipes->fetchAll();
Is it valid to set the PHP variable $tags to the MySQL wildcard %? if not possible then what should I do to make my query work?
When I run that code and there's not $_GET['tag'] is written the query will not fetch any posts from the database.

Using Wildcards in Prepared Statements With PDO
When using a wildcard in MySQL you must use the LIKE operator. It is correct to bind the wildcard with parameters in PDO.
You would prepare your statement like so.
$get_recipes = $con->prepare ("SELECT * FROM recipes WHERE tags LIKE ?");
And then you would bind your parameter using the % character, like so.
$get_recipes->execute(array('%'));
While that is the correct way to use a wildcard in the way you've proposed, that is not the correct solution to do what you're trying to do.
How to achieve what you're trying to achieve
In your code it looks like you want to select all rows if $_POST['tags'] is not set, and if it is set you want to select all rows that have the tags column set to the value of $_POST['tags']. To do this, you would want to prepare your statement inside the conditional, like so.
if (!isset($_GET['tag'])) {
$get_recipes = $con->prepare ("SELECT * FROM recipes");
$get_recipes->execute();
} else {
$get_recipes = $con->prepare ("SELECT * FROM recipes WHERE tags = ?");
$get_recipes->execute(array($_GET['tag']));
}
$recipes = $get_recipes->fetchAll();

Related

How do I use a variable in the WHERE condition of a MySQL query using a php variable? [duplicate]

This question already has answers here:
How to insert values in a PHP array to a MySQL table?
(2 answers)
Closed 5 years ago.
I'm using PHP session variable to track character ID's between two tables, characters and character_data_store.
The session ID definitely has the correct ID as I have had to print its value before it goes into the mySQL query.
For testing I selected a user I knew had a rapsheet and used
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.`key` = 'RapSheet'
AND character_data_store.character_id = '216'";
Obviously I can't use this for all users as I need to confirm the right one has been selected so thats where the session variable comes in.
I've tried using:
$correctPlayer = $_SESSION['selpid'];
echo $correctPlayer; #confirm it's the right id and then remove
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.'key' = 'RapSheet'
AND character_data_store.character_id = '$correctPlayer'";
I did some searching on SO and I found that int's need to have double quotes around them not single quotes, I tried that and had no luck but someone else suggested putting the session ID in exactly which I tried next:
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.'key' = 'RapSheet'
AND character_data_store.character_id = {$_SESSION['selpid']}";
Each time I do this I get mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given which SO tells me is because this operation results to false, I assume because it's not accepting the playerID from selpid or $correctPlayer?
It definitely works with the testing user where the playerID is inserted directly into the query. But I can't think of a way to do that since I need to match the playerID from table "characters" where the search is done against their first and last name and then pull the rapsheet data against the same playerID in table "character_data_store".
How do I use a variable in the WHERE condition of a MySQL query using a php variable?
You have obvious error in your code. You are missing quotes in {$_SESSION['selpid']} and you are using quotes in column name. Your query should be
$usersql = "SELECT * FROM character_data_store WHERE character_data_store.`key` = 'RapSheet' AND character_data_store.character_id = '{$_SESSION['selpid']}'";
You should not use quotes in column name, instead use backquotes(`) if you really need. I recommend prepared statements.
There are multiple ways to do this. A naive way to do this would be-
$usersql = "SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ".$correctPlayer;
But to avoid sql injections I would recommend you use bindparam function to bind paramaters in a statement.
$sql="SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ?";
if($stmt = $dbh->prepare($sql)){
$stmt->bindParam(1, $correctPlayer, PDO::PARAM_STR);
$ql = $stmt->execute() or die("ERROR: " . implode(":", $dbh->errorInfo()));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$result['data'] = $row;

PDO "ORDER BY" only works when hardcoding [duplicate]

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 9 years ago.
I want to fetch results from a MySQL database with PDO. The user should be able to order them by tablerow by which type (ascending or descending). This seems to only work when you hardcode it.
Does work:
$query = "SELECT * FROM ".$config->dbPrefix."content
WHERE cat_id = 2
ORDER BY id DESC
";
$query = $pdo->prepare($query);
$query->execute();
$result = $query->fetchAll();
Doesn't work:
$orderRow = 'id'; //from $_POST
$orderType = 'DESC' //from $_POST
$query = "SELECT * FROM ".$config->dbPrefix."content
WHERE cat_id = 2
ORDER BY :orderRow :orderType
";
$query = $pdo->prepare($query);
$query->bindValue(':orderRow', $orderRow);
$query->bindValue(':orderType', $orderType);
$query->execute();
$result = $query->fetchAll();
So my question is: what is the best way to do this and why isn't this implemented?
The best way I can think of is using a switch statement and writing the query for every different option which would have like 14 different available cases.
You can only provide placeholders for values in an SQL statement, not for column names or other kind of identifiers.
So instead of using bindValue, put the values in like you do for #config->dbPrefix, directly into the string. Make sure however that no SQL injection is possible.

Dynamically change column name in PDO statement [duplicate]

This question already has an answer here:
Can I use a PDO prepared statement to bind an identifier (a table or field name) or a syntax keyword?
(1 answer)
Closed 3 years ago.
Is it possible pass a column name as parameter in a prepared MySQL statement? Take the following example:
UPDATE Images
SET :placement = :imageURL
WHERE ID = :titleID;
PDO adds ' around each parameter, so the middle line above becomes:
SET 'Homepage' = '1.jpg'
Which MySQL doesn't like. Is there a way to include parameters for fieldnames in PDO statements and have them accepted?
Otherwise I guess I'll have to write several different PDO statements, depending on what's been chosen(?).
You would need to do something like this:
$column = 'someColumn';
$stmt = $db->prepare("UPDATE tableName SET {$column} = :columnValue WHERE ID = :recordId");
Parameterized placeholders are only for values.
I would suggest you read the comment #YourCommonSense posted on your question.
In situations such as this, I use a different sort of replacement parameters, like so:
$unitLabel = 'store_number';
$sql = 'select * from users where [unitLabel] = :unit and level = :level;';
$sql = str_replace('[unitLabel]', $unitLabel, $sql);
$params = array(
':unit' => 300,
':level' => 'admin',
);
$stmt = $dbh->prepare($sql);
$stmt->execute($params);
The prepared SQL query ends up being processed (more or less) as:
SELECT * FROM USERS WHERE store_number = 300 AND level = 'admin';
Which works for my situation. I hope this helps. :)

Using LIKE in bindParam for a MySQL PDO Query [duplicate]

This question already has answers here:
How do I create a PDO parameterized query with a LIKE statement?
(9 answers)
Closed 4 months ago.
I've read multiple examples on how these queries should be written but I'm struggling to get this specific like to run when using bindParam
Would this be the correct way to match usernames that begin with a?
$term = "a";
$term = "'$term%'";
$sql = "SELECT username
FROM `user`
WHERE username LIKE :term
LIMIT 10";
$core = Connect::getInstance();
$stmt = $core->dbh->prepare($sql);
$stmt->bindParam(':term', $term, PDO::PARAM_STR);
$stmt->execute();
$data = $stmt->fetchAll();
No, you don't need the inner single quotes so just $term = "$term%";
The statement you're running now would try to match 'a%' instead of a%
bindParam will make sure that all string data is automatically properly quoted when given to the SQL statement.
You can use bindValue , suppose you are having a $query = "search string"
$stmt->bindValue(':term', $query.'%'); // this will do like search for "search term XXXXX"
similarly
$stmt->bindValue(':term', '%'.$query.'%');
or
$stmt->bindValue(':term', '%'.$query);

How to use PHP string in mySQL LIKE query? [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Correct way to use LIKE '%{$var}%' with prepared statements?
(1 answer)
Closed 1 year ago.
I am trying to find the number of rows that match a specific pattern. In this example, all that START with "123":
This is working:
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '123%'");
$count = mysql_num_rows($query);
The problem is the LIKE will vary, so I'm trying to define it in the script, then execute the query, but this is NOT working:
$prefix = "123";
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE $prefix.'%'");
$count = mysql_num_rows($query);
How can I get this query to work properly in the second example?
EDIT: I've also tried it without the period (also not working):
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE $prefix'%'");
You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");
You can confirm this by printing out the string to see that it turns out identical to the first case.
Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:
$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
mysql_real_escape_string($prefix));
$query = mysql_query($sql);
Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.
DO it like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");
Do not forget the % at the end

Categories