My code checks if there is $GET value, if not then assign ALL values of array.
Seems like simple thing,not sure why its not working.
if(isset($_GET["smonth"])) {$smonth= $_GET["smonth"];
}
else {$smonth =12;} working , but not what I want
else {$smonth =array (1,2,3,4,5,6,7,8,9,10,11) ;}
After that I would like to use it in SQL :
and d.month_of_year = '".$smonth."%'
That would be something like
and month_of_year = (all values of array) or 1 value)
My Question:
What would be best solution to check, if active month is available? If not, assign All months to query.Thank You
The built-in PHP functions of in_array and implode should solve your issue:
in_array('1', $_GET["smonth"]); // checks if January is in $_GET["smonth"]
implode("," , $_GET["smonth"]); // Pull all of the values out of $_GET["smonth"] as a A STRING
Try in your statement and d.month_of_year IN (" . implode(',', $smonth) . ")
= operator checks for single value. If you want to check multiple values, use in.
and d.month_of_year in (".$smonth.")
You also have a % there, which works with LIKE queries.
<?php
if(isset($_GET['month'])){
$month = date('m'); //This would give you the index of the current month.
$array = array('01','02','02');
$query = "select * from table where month = ";
if(in_array($month,$array)){
$query = "select * from table where month = '".$month."'";
//Then query here
}
else
{
$query = "select * from table";
$where = "";
foreach($month as $m){
$where .= ' month = "'.$m.'" and ';
}
//There would be a ending and pls just try remove it
$query .= $where;
// then query here
}
}
?>
Related
I have a web application and I'm trying to modify one of the queries. The query fetches information (from a table named voyage_list) and returns various fields.
I want to modify the query so that it is based on certain filters the user applies (which will be placed in the URL).
I can't get the query to work in the web application, but if I copy the query and execute it directly within PHPMyAdmin, it works fine.
$vesselFilter = $_GET['vesselFilter'];
$vesselArray = explode(',', $vesselFilter);
$arrayCount = count($vesselArray);
$sqlExtend = ' status = 1 AND';
foreach ($vesselArray as $value) {
$i = $i + 1;
$sqlExtend .= " vesselID = '$value'";
if ($i < $arrayCount){
$sqlExtend .= " OR";
}
}
$newQuery = "SELECT * FROM voyage_list WHERE" . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
I appreciate the above is pretty messy, but it's just so I can try and figure out how to get the query to work.
Any help would be greatly appreciated!
Thanks
That query probably doesn't return what you think it does. AND takes precedence over OR, so it will return the first vessel in the list if the status is 1, and also any other vessel in the list, regardless of status.
You'd do better to create a query with an IN clause like this:
SELECT * FROM voyage_list WHERE status = 1 AND vesselID IN(8,9,10)
Here's some code to do just that:
$vesselFilter = $_GET['vesselFilter'];
// Validate data. Since we're expecting a string containing only integers and commas, reject anything else
// This throws out bad data and also protects against SQL injection.
if (preg_match('/[^0-9,]/', $vesselFilter)) {
echo "Bad data in input";
exit;
}
// filter out any empty entries.
$vesselArray = array_filter(explode(',', $vesselFilter));
// Now create the WHERE clause using IN
$sqlExtend = 'status = 1 AND vesselID IN ('.join(',', $vesselArray).')';
$newQuery = "SELECT * FROM voyage_list WHERE " . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
var_dump($query);
I am working on a PHP file and getting via POST this string:
$temas = $_POST['temas']; //$temas = ".45.12.34"
Where each of the numbers should be the id for a table record.
And I have following query
$query = "SELECT * FROM tb_preguntas WHERE tema = '".$temas."'";
I need to put in the WHERE part of the query each of the received id
Something like that: ... WHERE tema = 45 OR tema = 12 OR tema = 34
Of course, on each execution the string changes.
I have tried using the PHP explode function, but I don't know how to implement the result in the query.
My answer won't differ too much from everyone else's but it is an answer to address SQL injection + a solution
$temas = implode(',', explode('.', $_POST['temas']));
$temas = trim($temas);
$res = $conn->prepare('select * from `tb_preguntas` WHERE `tema` in (:temas)');
$res->execute(array(':temas' => $temas));
here we use a prepared statement, now you're code is safe woop woop
As suggested above you can use the IN() function of mysql, however you have to remove the first period '.' and change the rest to commas ','.
$query = "SELECT * FROM `tb_preguntas` WHERE `tema` IN('".str_replace('.',',',trim($temas,'.'))."') ";
best case scenario
$temas = implode(',', explode( '.', $_POST['temas']));
$query = "select * from tb_preguntas WHERE tema in (" . $temas . ")";
but your case, . comes first that makes life so much harder, so a better solution would be
$temas1 = explode( '.', $_POST['temas'] );
$temas2 = array();
foreach( $temas1 as $value ) {
if( is_numeric( $value )) $temas2[] = $value;
}
$query = "select * from tb_preguntas WHERE tema in (" . implode( ',' , $temas2 ) . ")";
Use explode() to split those numbers by .And it must turn into array.
Then run your queries into a loop using the lenth of the array like this:
$id = explode('.',$temas);
foreach($id as $temas_id) {
$query = "SELECT * FROM tb_preguntas WHERE tema = '".$temas_id."'";
if(isset($conn->query(query ))) {
// Execute code here if there's a result.
}
}
Please try this code.
$temas = $_POST['temas'];
$temas = explode('.',$temas);
$query = mysql_query("SELECT * FROM test_stipe WHERE tema in '".implode("', '", $temas)."'");
This code is working fine.
Alright,
I've got a multiple select dropdown on a page called week-select, its selections get passed via ajax to my php page.
I can get the data just fine, but when the query runs it doesn't complete appropriately.
I've got this:
//Deal with Week Array
$weekFilter = $_GET['week']; /*This is fine, if it's 1 week the query works great (weeks are numbered 12-15), but if it is 2 weeks the result is formatted like this 12-13 or 13-14-15 or whichever weeks are selected*/
$weekFilter = str_replace("-",",",$weekFilter); /*This works to make it a comma separated list*/
.../*I deal with other variables here, they work fine*/
if ($weekFilter) {
$sql[] = " WK IN ( ? ) ";
$sqlarr[] = $weekFilter;
}
$query = "SELECT * FROM $tableName";
if (!empty($sql)) {
$query .= ' WHERE ' . implode(' AND ', $sql);
}
$stmt = $DBH->prepare($query);
$stmt->execute($sqlarr);
$finalarray = array();
$count = $stmt->rowCount();
$finalarray['count'] = $count;
if ($count > 0) { //Check to make sure there are results
while ($result = $stmt->fetchAll()) { //If there are results - go through each one and add it to the json
$finalarray['rowdata'] = $result;
} //end While
}else if ($count == 0) { //if there are no results - set the json object to null
$emptyResult = array();
$emptyResult = "null";
$finalarray['rowdata'] = $emptyResult;
} //end if no results
If I just select one week it works great and displays the appropriate data.
If I select multiple options (say weeks 12, 14 and 15) it runs the query but only displays week 12.
When I manually input the query in SQL, how I imagine this query is getting entered - it runs and displays the appropriate data. So if I put SELECT * FROM mytablename WHERE WK IN ( 12, 14, 15 ) it gets exactly what I want.
I can't figure out why my query isn't executing properly here.
Any ideas?
**EDIT: I make the array from the multiple selections a string using javascript on the front end before it is passed to the backend.
Your resulting query with values probably looks like this with a single value in IN:
… WK IN ("12,14,15") …
Either use one placeholder for each atomic value:
if ($weekFilter) {
$values = explode(",", $weekFilter);
$sql[] = " WK IN ( " . implode(",", array_fill(0, count($values), "?")) . " ) ";
$sqlarr = array_merge($sqlarr, $values);
}
Or use FIND_IN_SET instead of IN:
$sql[] = " FIND_IN_SET(WK, ?) ";
I don't think you can bind an array to a singular ? placeholder. Usually you have to put in as many ? values as there are elements in your array.
If your HTML is correct and your week select has name="week[]", then you will get an array back with $_GET['week'];, otherwise without the [] it will only give you 1 value. Then, you're doing a string replace, but it's not a string. Instead, try this:
$weekFilter = implode(',', $_GET['week']);
I am trying to be lazy (or smart): I have 7 checkboxes which correlate with 7 columns in a MySQL table.
The checkboxes are posted in an array:
$can = $_POST['can'];
I've created the following loop to dump the variables for the MySQL insert:
for($i=1;$i<8;$i++){
if($can[$i] == "on"){
${"jto_can".$i} = 'Y';
}
else{
${"jto_can".$i} = 'N';
}
}
print_r($jto_can1.$jto_can2.$jto_can3.$jto_can4.$jto_can5.$jto_can6.$jto_can7);
This correctly outputs:
YYNYYYY
However, when I attempt to use those variables in my MySQL update, it doesn't accept the changes.
mysqli_query($db, "UPDATE jto SET jto_can1 = '$jto_can1', jto_can2 = '$jto_can2', jto_can3 = '$jto_can3', jto_can4 = '$jto_can4', jto_can5 = '$jto_can5', jto_can6 = '$jto_can6', jto_can7 = '$jto_can7' WHERE jto_id = '$id'")or die(mysqli_error($db));
Can anyone explain why the print_r displays the variables whereas MySQL update does not?
Stick with the array, and form the query dynamically:
$sql = 'UPDATE jto SET ';
$cols = array();
foreach( range( 1, 7) as $i) {
$value = $_POST['can'][$i] == 'on' ? 'Y' : 'N'; // Error check here, $_POST['can'] might not exist or be an array
$cols[] = 'jto_can' . $i . ' = "' . $value . '"';
}
$sql .= implode( ', ', $cols) . ' WHERE jto_id = "' . $id . '"';
Now do a var_dump( $sql); to see your new SQL statement.
this is not a mysql problem. mysql will only see what you put into that string. e.g. dump out the query string BEFORE you do mysql_query. I'm guessing you're doing this query somewhere else and have run into scoping problems. And yes, this is lazy. No it's not "smart". you're just making MORE work for yourself. What's wrong with doing
INSERT ... VALUES jto_can1=$can[0], jto_can2=$can[1], etc...
ok so I've been trying for a while now to get this to work but there has to be a better solution than what im thinking about. I'm fairly new to php/mysql so not sure how to do the following:
I have a search box that contains dropdowns for country, state, city
Now if the user only selects country and clicks on search it needs to filter the select by just country and show everything else.
if(!empty($_REQUEST['city']))
$city = $_REQUEST['city'];
else
$city= "%";
if(!empty($_REQUEST['state']))
$state= $_REQUEST['state'];
else
$state= "%";
if(!empty($_REQUEST['country']))
$country= $_REQUEST['country'];
select * from table where country = $country and state = $state and city = $city
problem with this is that those columns are ints so I can't use the "%" to filter it. I hope I was able to explain it any help is more than welcome. Thanks in advance
If you don't want to constrain a column, simply omit it from your query
never insert a string from $_REQUEST directly into a query string -- classic SQL injection flaw.
you probably want to enforce some sort of limit, lest the query return every single result in your database.
example:
<?php
$conditions = array();
if(!empty($_REQUEST['city']))
$conditions[] = "city = " . mysql_real_escape_string($_REQUEST['city']);
if(!empty($_REQUEST['state']))
$conditions[] = "state = " . mysql_real_escape_string($_REQUEST['state']);
if(!empty($_REQUEST['country']))
$conditions[] = "country = " . mysql_real_escape_string($_REQUEST['country']);
$sql = 'select * from table ';
if(!empty($conditions))
$sql .= ' where '. implode(' AND ', $conditions);
$sql .= ' LIMIT 1000';
$where = array();
if(!empty($_REQUEST['city'])) $where[] = "city = '".(int)$_REQUEST['city']."'";
if(!empty($_REQUEST['state'])) $where[] = "state = '".(int)$_REQUEST['state']."'";
if(!empty($_REQUEST['country'])) $where[] = "country = '".(int)$_REQUEST['country']."'";
$wherestring = if(count($where) != 0) ? " WHERE ".implode(' AND ', $where) : "" ;
$query = "SELECT * FROM table".$wherestring;
You may want to consider writing several query strings, one for just country, one for state and country and one for city, state and country. Alternatively you can assemble the query string based upon the different parameters you have to work with.
Example:
if(isset() || isset() || isset() ) //make sure at least one is set
{
$query_string = "SELECT * FROM table WHERE ";
if(isset($_REQUEST['country']))
{
$country = $_REQUEST['country'];
$query_string .= " country = $country";
}
if(isset($_REQUEST['state']))
{
$state = $_REQUEST['state'];
$query_string .= " state = $state";
}
if(isset($_REQUEST['city']))
{
$city = $_REQUEST['city'];
$query_string .= " city = $city";
}
}
else
{
//Else, if none are set, just select all the entries if no specifications were made
$query_string = "SELECT * FROM table";
}
//Then run your query...
So in english, the first thing you do is check your parameters, making sure you have something to work with before you try and concatenate empty variables together.
Then you make the base query string (as long as we have parameters) and leave it open ended so that we can add whatever parameters you need.
Next check each parameter, and if it is set, then concatenate that parameter onto the end of the query string.
Finally process the query by sending it to the SQL server.
Good luck!
h
Here're my suggestions.
I'm giving you an answer, even though you have three already. I'm thinking mine may be easier on the code-eyes.
Do not use the raw $_REQUEST value, as it's likely that the user can poison your database by feeding it fake $_REQUEST data. Though there may be better ways to do it, keep in mind the command "mysql_real_escape_string($string)".
A common method I've seen for solving this problem is written below. (The implode idea, basically. Frank Farmer does it as well in his.)
-
$__searchWheres = array(); //Where we'll store each requirement used later
foreach( array('city','state','country') as $_searchOption) {
if ( ! empty( $_REQUEST[$_searchOption] ) ) {
$__searchWheres[] = $_searchOption . '= "' . mysql_real_escape_string( $_REQUEST[$_searchOption] ) . '"';
}
}
$__query = 'select * from table' . (count($__searchWheres) > 0 ? ' WHERE ' . implode(' AND ',$__searchWheres) : ''); //Implode idea also used by Frank Farmer
//Select from the table, but only add the 'WHERE' key and where data if we have it.
mysql_query($__query);