I'm having some trouble with what I believe should be some fairly simple PHP. It's run inside of WordPress, but the question shouldn't be WordPress specific. The $wpdb->get_results() is just a way to query the WordPress database without having to use a connection string. I also use a couple of $_GET commands.
Here's what I have so far:
$Data = $wpdb->get_results("SELECT *
FROM database.table
WHERE sem.MonthNum >= " .$_GET["minMonth"]. "
AND sem.MonthNum <= " .$_GET["maxMonth"]. "
AND sem.Year >= " .$_GET["minYear"]. "
AND sem.Year <= " .$_GET["maxYear"]. ");
This works, so long as the $_GET is populated. I'd like to add a kind of default value such that if $_GET is empty, a number is set, and if it's not empty, it grabs that number. Something along the lines of...
$Data = $wpdb->get_results("SELECT *
FROM database.table
WHERE sem.MonthNum >= " if(!$_GET){echo 1;} else {echo ".$_GET[\"minMonth\"]. "} "
But that doesn't work for me...probably some silly PHP syntax error, I'm not sure about all the echo statements and the quotes within other quotes and whatnot.
For each of your variables do this:
$minMonth = isset($_GET["minMonth"]) ? intval($_GET["minMonth"]) : 1;
...
"WHERE sem.MonthNum >= " .minMonth. "
The intavl() call will make convert the $_GET value to an integer if it is not already, which will protect you from SQL injection security issues. If you need to do something similar with strings, use something like mysql_escape_string() instead.
You could add a variable for each, for example:
// If not set $minMonth is set to 1
$minMonth = (isset($_GET['minMonth']) ? $_GET['minMonth'] : 1);
Just do this for the other variables as well.
You can use short hand notation like Scott and David show directly in your query:
$Data = $wpdb->get_results("SELECT *
FROM database.table
WHERE sem.MonthNum >= ".(!isset($_GET['minMonth'])?'1':$_GET['minMonth'])."
AND...
You really need to sanitize the variables first though, otherwise you could be SQL injected very easily.
Related
I'm trying to execute this sql query using PHP
$sql="SELECT convert (varchar(500),Xml.query('for $i in /data/var1/text() return concat($i, "||")')) as var1 FROM #table1";
echo $sql;
$result = odbc_exec($connection, $sql);
i have a problem with $i, the variable is used in the loop in the sql query .
I tried to put it between singles quotes and doubles quotes, i also tried this : \'$i\' but it's not working.
If you $i is php variable, than you have to inject it like in code below:
$sql="SELECT convert (varchar(500),Xml.query('for ".$i." in /data/var1/text() return concat(".$i.", \"||\")')) as var1 FROM #table1";
I also escaped double quotes that you used in concat() function, they surely wouldn't work as you wrote it, but I'm not 100% sure if that way of escaping them gonna work - personally I'm avoiding similar situations.
I have a variable that is a filter for my query:
$filterString.=" AND venue = ".$venue;
And I want this variable (when called) to add the AND filter statement to my query.
My query is as follows (with the failed attempt):
mysql_query("SELECT * FROM event
WHERE city = '$city' " . $filterString . "
ORDER BY date ASC");
I think the venue needs to be surrounded by single quotes:
$filterString.=" AND venue = '".$venue.".";
However, it is better to use parameterized queries, instead of embedding queries directly in the SQL string.
You could use:
$filterString .= !empty($venue) ? " AND venue = '$venue'" : '';
Substitute whatever test you want at the start, the idea is to return a blank string if $venue doesn't apply to the filter.
To answer your other comment question:
WHERE 1
is a valid condition that works like Anything
I have a PHP function that makes a query to MySQL DB.
function regEvent($event, $l)
{
$sqlz_upd="UPDATE {$event} SET f1a='$_POST[F1A"'.$l.'"]'";
The question is what is the syntax to use variable $l in $_POST[F1A$l]?
$condition = $_POST["F1A" . $l];
$sqlz_upd="UPDATE {$event} SET f1a='".mysql_real_escape_string($condition)."'";
This is how to use your dynamic post and be safe for Sql Injection.
Here you go:
$var = mysql_real_escape_string($_POST["F1A".$l]);
$sqlz_upd="UPDATE {$event} SET f1a='$var' ";
if you are using a string as key in an associative array. It should be enclosed in single or double quotes(though PHP won't give any error).
i.e. $_POST['F1A'. $l] or $_POST["F1A$l"]
my suggestion will be...
$sqlz_upd="UPDATE {$event} SET f1a='" . $_POST["F1A$l"] . "'";
Is there any way to check if a column is "anything"? The reason is that i have a searchfunction that get's an ID from the URL, and then it passes it through the sql algorithm and shows the result. But if that URL "function" (?) isn't filled in, it just searches for:
...AND column=''...
and that doesn't return any results at all. I've tried using a "%", but that doesn't do anything.
Any ideas?
Here's the query:
mysql_query("SELECT * FROM filer
WHERE real_name LIKE '%$searchString%'
AND public='1' AND ikon='$tab'
OR filinfo LIKE '%$searchString%'
AND public='1'
AND ikon='$tab'
ORDER BY rank DESC, kommentarer DESC");
The problem is "ikon=''"...
and ikon like '%' would check for the column containing "anything". Note that like can also be used for comparing to literal strings with no wildcards, so, if you change that portion of SQL to use like then you could pre-set the variable to '%' and be all set.
However, as someone else mentioned below, beware of SQL injection attacks. I always strongly suggest that people use mysqli and prepared queries instead of relying on mysql_real_escape_string().
You can dynamically create your query, e.g.:
$query = "SELECT * FROM table WHERE foo='bar'";
if(isset($_GET['id'])) {
$query .= " AND column='" . mysql_real_escape_string($_GET['id']) . "'";
}
Update: Updated code to be closer to the OP's question.
Try using this:
AND ('$tab' = '' OR ikon = '$tab')
If the empty string is given then the condition will always succeed.
Alternatively, from PHP you could build two different queries depending on whether $id is empty or not.
Run your query if search string is provided by wrapping it in if-else condition:
$id = (int) $_GET['id'];
if ($id)
{
// run query
}
else
{
// echo oops
}
There is noway to check if a column is "anything"
The way to include all values into query result is exclude this field from the query.
But you can always build a query dynamically.
Just a small example:
$w=array();
if (!empty($_GET['rooms'])) $w[]="rooms='".mysql_real_escape_string($_GET['rooms'])."'";
if (!empty($_GET['space'])) $w[]="space='".mysql_real_escape_string($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mysql_real_escape_string($_GET['max_price'])."'";
if (count($w)) $where="WHERE ".implode(' AND ',$w); else $where='';
$query="select * from table $where";
For your query it's very easy:
$ikon="";
if ($id) $ikon = "AND ikon='$tab'";
mysql_query("SELECT * FROM filer
WHERE (real_name LIKE '%$searchString%'
OR filinfo LIKE '%$searchString%')
AND public='1'
$ikon
ORDER BY rank DESC, kommentarer DESC");
I hope you have all your strings already escaped
I take it that you are adding the values in from variables. The variable is coming and you need to do something with it - too late to hardcode a 'OR 1 = 1' section in there. You need to understand that LIKE isn't what it sounds like (partial matching only) - it does exact matches too. There is no need for 'field = anything' as:
{field LIKE '%'} will give you everything
{field LIKE 'specific_value'} will ONLY give you that value - it is not partial matching like it sounds like it would be.
Using 'specific_value%' or '%specific_value' will start doing partial matching. Therefore LIKE should do all you need for when you have a variable incoming that may be a '%' to get everything or a specific value that you want to match exactly. This is how search filtering behaviour would usually happen I expect.
Let's say I have a query:
" SELECT * FROM table
WHERE donor_id = " .$this->session->userdata('id') ."
GROUP BY rating"
However, it appears that I get a mysql syntax error here, citing that $this->session->userdata('id') gives me '25' for example, instead of 25. Are there any workarounds here to prevent $this->session->userdata('id') from being quoted?
Thanks.
In CI, I do this all the time:
$id = intval($this->session->userdata('id'));
$sql = " SELECT * ".
" FROM table ".
" WHERE donor_id = {$id} ".
"GROUP BY rating ";
//process $sql below
Creating query like this will make you easier to spot bug and prevent SQL injection. Use concatenation when you need to split query to multiple lines instead of make it a long multiple string is to prevent the actual query string got too long. Indent the SQL keyword is to make it easier spot logical and syntax bug.
intval($this->session->userdata('id'))
Assuming you mean that it is returning you a string instead of an integer you could always try using settype or intval:
$var = '2';
settype($var, "integer");
$var = intval($var);
However, if you mean that the quotes are for some reason hard-coded in, you could do a string replace, if you are sure that the value will not contain quotes:
ech str_replace("'", "", "'2'"); // prints 2