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
Related
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();
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;
This question already has answers here:
MySQL query not working while using php variable in where clause
(3 answers)
Closed 8 years ago.
I am new to php so hopefully someone could point out where i am going wrong
I have written a php code to fetch certain records from an MySQL database
I am running the query as
$result = mysql_query("SELECT * FROM Messages where Id='idLo'")
or die(mysql_error());
i get no results
but when i hard code like
$result = mysql_query("SELECT * FROM Messages where Id='4'")
or die(mysql_error());
It returns all the data
What am i misisng
i am collecting idLo as a get parameter
$idLo = $_GET['id'];
Your code needs to change to
$result = mysql_query("SELECT * FROM Messages where Id='$idLo'") or die(mysql_error());
From
$result = mysql_query("SELECT * FROM Messages where Id='idLo'") or die(mysql_error());
There is basic thing that in php every variable has dollar( $ ) sign that we need to use every time while using it.
Try this:
$result = mysql_query("SELECT * FROM Messages where Id='$idLo'");
you forgot $ in front of idLo in your query.
$result = mysql_query("SELECT * FROM Messages where Id='".$idLo."'");
should do it
It appears that you haven't included the "$" to signify that idlo is a variable:
where Id='idLo'
should be
where Id='$idLo'
Also, you might want to have a look into using PDO or Mysqli for accessing your mysql database through PHP.
you should user mysqli pr PDO by now. A bit better:
$result = $connection->query("SELECT * FROM Messages where Id='$id'");
also, check if Id is really with capital letters and add a dollar sign to the variable name.
$idLo = $_GET['id'];
$result = mysql_query("SELECT * FROM Messages where Id='$idLo'") or die(mysql_error());
I'm having trouble using variables in my SQL WHERE clause. I'm getting this error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL
result resource
The code is:
$sql3= mysql_query("SELECT COUNT($ww) FROM data WHERE $".$ww." = ".$weeknumber." ");
What am I doing wrong?
Why don't you count the table column by putting the columns name in your COUNT(column_name)?
Like so:
$sql3= mysql_query("SELECT COUNT(week_num) as wknum FROM data WHERE '$ww' = '$weeknumber'");
$counted_weeks["week_num"]
// $counted_weeks["week_num"] will output your sum
//week_num would be a column name from your "data" table
I recommend looking at this link. As #Crontab mentioned I am not sure why you have a dollar sign in front of your where clause.
A couple other things to point out:
As it says in the link, you will need to make sure the query text is properly escaped. Also, If I'm not mistaken (not familiar with PHP) do you need to explicitly concatenate the text instead of just using quotes? (i.e. instead of "SELECT ... " ... " do you need to do "SELECT ... " + " ... ")
php string formatting is perfect here, take your messy confusing concat string and make it clean and readable!
$sql3= mysql_query(sprintf("SELECT COUNT(%s) FROM data WHERE %s=%d", $ww, $ww, $weeknumber));
Assuming that $ww is a valid column name and $weekNumber is an integer, this should work:
$query = "SELECT COUNT(*) AS cnt FROM data WHERE $ww = '$weekNumber'";
$rs = mysql_query($query);
$r = mysql_fetch_assoc($rs);
echo "Count: {$r['cnt']}";
I am guessing $ww is referring to a column name. $weekNumber is obviously the value. In that case, your SQL query should look like this:
$sql3= mysql_query("SELECT COUNT(".$ww.") FROM data WHERE ".$ww." = ".$weeknumber." ");
I'm not a PHP guy, but I'm assuming you have the correct PHP syntax.
Alt A below is a statement from a php-mysql tutorial. It works as it should.
I found the id-value rather obfuscated and tested alt B. This also worked!
What is the point with the id-value of alt A?
MySQL 5.0.51, PHP 5.2.6
// Alt A :
$sql = "SELECT * FROM example WHERE id = '".$q."'";
// Alt B :
$sql = "SELECT * FROM example WHERE id = $q";
This are just two different approaches to building a string from static and variable data.
Alternative A uses concatenation, or the joining of string and variable tokens using the concatenation operator.
Alternative B uses variable expansion, wherein the variables inside a double-quote-delimited string are expanded to their values at evaluation time.
Neither is necessarily better or preferred, but if you have to have single-quote-delimited strings, for example, then you would need to use alternative A.
Of course, neither of these is preferable to building SQL queries with bound parameters, as not doing so leaves you vulnerable to SQL injection attacks.
Theres two reasons to use the example in 'Alt A'. First is if the string is enclosed in single quotes '', the variable's name will be used in the string instead of it's value.
$id = 7;
'SELECT * FROM table WHERE id = $id' //works out to: WHERE id = $id
"SELECT * FROM table WHERE id = $id" //works out to: WHERE id = 7
Secondly, it's useful to combine strings with the results of a function call.
"SELECT * FROM table WHERE id = '".getPrimaryId()."'"
Outside of what has already been said I've found it best practice, if I'm writing a query, to write it as so:
$sql = "SELECT * FROM table WHERE uid=" . $uid . " LIMIT 1";
The reason for writing SQL like this is that 1. MySQL query doesn't have to parse the PHP variables in the Query and 2 you now easily read and manage the query.
When PHP communicates with MySQL, it is actually (in essence) two languages communicating with each other. This means that a string will be processed by the first language before being sent to the other. It also means that it is important to think in terms of the receiving language
In this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = $q";<br/>
you are telling MySQL to
"SELECT * FROM example1 WHERE id = some_name.
In this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = '$q'";<br/>
and this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = '".$q."'";<br/>
you are telling MySQL to
"SELECT * FROM example1 WHERE id = 'some_name'.
The first example should cause an error as some_name is not a valid part of a MySQL query (in that context). On the other hand, the next two will work fine, because MySQL will look for the String "some_name".
You can also do this:
$sql="SELECT * FROM exempel WHERE id = {$q}";
which is useful for setting off things like:
$sql="SELECT * FROM exempel WHERE id = {$row[id]}";
in 'alt B', $q must be an int or float or other numeric
in 'alt A', $q can be anything a string, int, etc.
The single quote makes that possible. It's just hard to see sometimes if you are looking at it for the first time.