Issue with a mysql query where (IN) - ' and " - php

I have an issue with a sql query.
The query works until I add the third line :AND procurements.activity1 IN("'.$arr.'")'.
I guess the ' and " are not properly set.
IN $arr is an array..
Security checks are not an issue here, they are being dealt with.
My question is all about the IN("'.$arr.'")' line, really.
Thanks so much in advance for your help.
if (isset($_GET['continent'])) {$requete= 'countries.region = "'.$continent.'"';}
if (isset($_GET['pays'])) {$requete=''.$requete.' AND countries.code_iso="'.$pays.'"';}
if (isset($_GET['activity1'])) {$requete=''.$requete.' AND procurements.activity1 IN("'.$arr.'")';}
if (isset($_GET['type_org'])) {$requete=''.$requete.' AND organisations.type_org="'.$type_org.'"';}
$query = $mysqli->query('SELECT
countries.code_iso,
countries.region,
countries.fr,
countries.en,
countries.flag,
procurements.id,
procurements.ref_org,
procurements.ref_bid,
procurements.activity1,
procurements.url,
procurements.code_cpv,
procurements.date_entered,
procurements.date_expire,
procurements.country_exec,
organisations.ref_org,
organisations.name_organisation,
organisations.type_org,
organisations.cp,
organisations.city,
organisations.country
FROM countries, procurements, organisations
WHERE countries.code_iso = procurements.country_exec
AND organisations.ref_org = procurements.ref_org
AND '.$requete.'');

First of all, if you want to append something you your variable instead of this:
$requete=''.$requete.'
use $requete .= ' AND countries.code_iso="'.$pays.'"';..
About your IN("'.$arr.'")', if $arr is an php array then you cannot assign it to your query like that, instead use use implode to combine your array into a string..

The initial problem appears to be that you are trying to just concat in an array. However from your comment this is not the case.
However you state you use:-
$arr = implode(',', $_GET['activity1']);
But with your code of:-
if (isset($_GET['activity1'])) {$requete=''.$requete.' AND procurements.activity1 IN("'.$arr.'")';}
you would land up with something like:-
AND procurements.activity1 IN("1,2,3")
Either change
$arr = implode(',', $_GET['activity1']);
to
$arr = implode('","', $_GET['activity1']);
or change
if (isset($_GET['activity1'])) {$requete=''.$requete.' AND procurements.activity1 IN("'.$arr.'")';}
to
if (isset($_GET['activity1'])) {$requete=''.$requete.' AND procurements.activity1 IN('.$arr.')';}

you can use this code
$requete = '';
if (isset($_GET['continent'])) {$requete = ' AND countries.region = "'.$continent.'"';}
if (isset($_GET['pays'])) {$requete .=' AND countries.code_iso="'.$pays.'"';}
if (isset($_GET['activity1'])) {$requete .=' AND procurements.activity1 IN("'.implode(',',$arr).'")';}
if (isset($_GET['type_org'])) {$requete .=' AND organisations.type_org="'.$type_org.'"';}
and in query remove "AND" before $requete variable

Related

Removing empty spaces and BR from string in echo

I got the below code but at the moment it generates a string of results but with about 40+ empty spaces.
$user_ = JFactory::getUser();
$db = JFactory::getDBO();
$levels = JAccess::getAuthorisedViewLevels($user->id);
foreach($levels as $key => $level)
{
$query = 'SELECT title FROM #__pf_projects';
$query .= ' WHERE access = ' . $level . " AND TRIM(title) != ''";
$db->setQuery($query);
$projectlist = $db->loadResult($query).'<br>';
echo $projectlist;
}
At first I thought that array_filter() would be good here but as PatrickQ points out it is a string so the array filter won't work.
Then I adapted the code according to the answer from Don't Panic. This adapted code is what you can see above.
It returns now a list like this.
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
http://www.domain1.com
<br>
<br>
<br>
<br>
http://www.domain5.com
http://www.domain23.com
http://www.domain65.com
http://www.domain213.com
<br>
<br>
<br>
<br>
<br>
<br>
So how to adapt the code to just get a list like this:
http://www.domain1.com
http://www.domain5.com
http://www.domain23.com
http://www.domain65.com
http://www.domain213.com
When you change the <br> into a , then the list becomes ,,,,,,,,,,,http,,,,,,httphttphttphttp,,,,,,, <= I wrote it down a bit shorter.
First thing, array_filter, if no callback was passed, will remove only falsy elements. String with empty spaces is evaluated to true and therefore will not be remove from array. You can do something like:
$filteredArray = array_filter($projectList, function($val) {
return trim($val);
});
print_r($filteredArray);
Also, you can't echo an array. You can use print_r or var_dump.
If array_filter isn't filtering out empty values, then they probably aren't really empty. Assuming there is some sort of whitespace there rather than nulls or empty strings, you can probably modify your query to trim the title and only return results where there's still something there.
SELECT title FROM #__pf_projects
WHERE access = ? AND title IS NOT NULL AND TRIM (title) != ''
Or, in terms of your original PHP code:
$query = 'SELECT title FROM #__pf_projects';
$query .= ' WHERE access = ' . $level . " AND TITLE IS NOT NULL AND TRIM(title) != ''";
It is best to avoid concatenating variables into your SQL like this, though. If the framework you're using has some way to utilize prepared statements, you should go that route instead.
If this still doesn't work, I don't really know what else to try with the query, but you should be able to just check for an empty result in PHP and only echo if there's something to show.
$projectlist = $db->loadResult($query);
if (trim($projectlist)) echo $projectlist.'<br>';
Thanks to everyone's answers I finally figured out a way to get the results. My way is not necessarily the right way for everyone. And someone with more knowledge then me in this area would probably do it different.
Essentially my answer is outputting the entire string with each result inside a div. This will create a lot of empty divs but those are not generated by HTML. They do however show up in the Inspector.
The final code that I use in my script.
$user_ = JFactory::getUser();
$db = JFactory::getDBO();
$levels = JAccess::getAuthorisedViewLevels($user->id);
foreach($levels as $key => $level)
{
$query = 'SELECT title FROM #__pf_projects';
$query .= ' WHERE access = ' . $level;
$db->setQuery($query);
$projectlist = '<div class="project">'.$db->loadResult($query).'</div>';
echo $projectlist;
}
This is now giving me a list like this:
http://www.domain1.com
http://www.domain5.com
http://www.domain23.com
http://www.domain65.com
http://www.domain213.com

How to select with array values in comma separated values in mysql

I'm not good at english so i appologise it for first.
I have an array value like this:
$a=['php','java','.Net']
please look at this link provided.
http://sqlfiddle.com/#!9/2c07a/4
How to make selection with the table.
Please help me guys...I thank you in advance...
Use FIND_IN_SET
PHP code:
$a=['php','java','.Net']
$query_part = '';
foreach($a as $v)
{
$query_part .= "FIND_IN_SET('$v',keyskills) OR ";
}
$query_part = trim($query_part, ' OR ');
$sql = "select jobid from jobfair where $query_part";
//select jobid from jobfair where FIND_IN_SET('php',keyskills) OR FIND_IN_SET('java',keyskills) OR FIND_IN_SET('.Net',keyskills);
If you want to return rows that match all values then use AND clause.
Reference: https://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set

PHP variable used in SQL

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
}
}
?>

PHP Search multiple words in query against database table

I have a user query and a database. My database contains tables. What I am curious to know, is my method for querying the database. What I'm thinking is:
Separate the query into an array split by a space
Loop through each word and do a LIKE '%{$word}%' OR
Above that, just prior to each iteration, do an 'AND'
The problem is, its not working correctly. Its not dicing done to precise emails that match my queries. Here is my code:
$i=0;
$userQuery = $_POST['q']; // q = "Jonathan gmail"
$sql = "SELECT * FROM addresses WHERE ";
$parts = explode(' ',$userQuery);
$cnt=count($parts);
foreach($parts as $part){
$part = mysql_real_escape_string($part);
if($i!==$cnt-1){
$sql.="(
addresses.name LIKE '%".$part."%' OR
addresses.localpart LIKE '%".$part."%' OR
addresses.domain LIKE '%".$part."%'
) AND
";
} else {
$sql.="(
addresses.name LIKE '%".$part."%' OR
addresses.localpart LIKE '%".$part."%' OR
addresses.domain LIKE '%".$part."%'
)
";
}
$i++;
}
}
My question is whats wrong with this logic? It seems accurate.
First of all: This will break on a single word.
Second: This is everything else but safe from an SQL attack.
Now - how I'd do it
$parts = preg_split('/[\s,]+/',$userQuery);
$sql=array();
foreach($parts as $part) {
$part=mysql_real_escape_string($part); //Or whatever works with your DB access framework
$sql[]="(addresses.name LIKE '%$part%' OR addresses.localpart LIKE '%$part%' OR addresses.domain LIKE '%$part%')";
}
$sql=implode(' AND ', $sql);
$sql="SELECT * FROM addresses WHERE $sql";
hey something like this:
foreach($parts as $key => $part){
$part=mysql_real_escape_string($part);
$sql .= sprintf("(
addresses.name LIKE %s OR
addresses.localpart LIKE %s OR
addresses.domain LIKE %s
)", $part);
if ($key!=($cnt-1)) {
$sql .= " AND ";
}
}
Little notice, you're using $i variable before initializing it. Also maybe it will be a better way to use REGEXP. Something like:
// $search_terms = '%Jonathan%|%gmail%'
$sql = "addresses.name REGEXP $search_terms OR addresses.localpart REGEXP $search_terms OR addresses.domain REGEXP $search_terms";
More details on REGEXP

Heep needed with str_replace

I face a problem with the str_replace function, see the code below :
$query = "SELECT title FROM zakov WHERE chnt='$atd_nad'";
$str = str_replace("Example.com_", "","$query");
$result = mysql_query($str) or die('Errant query: '.$str);
What I want is to replace the word " Example.com_ " with nothing "" but it did not work for me ! I do not know why.
In the row 'title' you can find something like this " Example.com_nameofsmthng "
So what I want is to keep just the word "nameofsmthng" and also to keep the begining of each word of it in capital letter to have finally somethin like "NameOfSmthng"
$atd_nad = 'Foobar Example.com_nameofsmthng Bazbat';
$query = 'SELECT title FROM zakov WHERE chnt="' . $atd_nad . '"';
$str = str_replace('Example.com_', '', $query);
echo $str; // SELECT title FROM zakov WHERE chnt="Foobar nameofsmthng Bazbat"
This works fine. Try it quickly. My assumption is that you mistyped $atd_nad or the value is incorrect.
Edit: hmm i think I misunderstood the example your trying to replace the string in the query string instead of the database?
You could make mysql do the replacement for you which should be faster then making php do it.
$query = "SELECT REPLACE(title, 'Example.com_', '') as newtitle FROM zakov WHERE chnt='$atd_nad'";
$resultset = mysql_query($query) or die('Errant query: '.$query);
$result = mysql_fetch_assoc($query);
echo $result['newtitle'];
Or you could replace all occurrences in the database with an update and then just select the title.
UPDATE zakov SET title = REPLACE(title, 'Example.com_', '');
Hope this helps.
while($row = mysql_fetch_assoc($result)) {
$title = str_replace("something", "", $row['title']);
}
Is what I believe you're looking for. Your code is trying to replace it in the query, which doesn't make sense. You need to replace it in the actual records. This will replace "something" with "". Alternatively, if you've already stored them in an an array or something you would just loop over the array and do the replacement. Basically: operate on the records, not on the query.

Categories