Filter an array using explode - php

My question is fairly simple. I have a column in my table labeled 'area' that appears like:
ma_south-coast
ma_south-caost
ma_north
ca_los-angelos
ca_los-angelos
I want to be able to select just the 'ma' ones. I am trying to do something such as:
$res_area = mysqli_query($connection,"select area from users");
while ($row_state = mysqli_fetch_array($res_area)) {
$state_exp = reset(explode("_", $row_state['area']));
}
Printing $state_exp at this point would give me: mamamacaca which is good. But I want to filter so I only get the ma ones.

You can extend your query with WHERE column LIKE "ma%" or check with substr($row_state['area],0,2) if the first two characters are "ma".

You could try this:
$res_area = mysqli_query($connection,"select area from users");
while ($row_state = mysqli_fetch_array($res_area)) {
$state_exp = stristr(reset(explode("_", $row_state['area'])),'ma');
}

You're looking for the LIKE operator. The LIKE operator is used to search for a specified pattern in a column.
Try this:
SELECT * FROM tablename WHERE areaLIKE 'ma_%';
You can read more about the LIKE operator here.

The optimal solution could be :-
$res_area = mysqli_query($connection,"select area from users WHERE area LIKE 'ma_*')";
while ($row_state = mysqli_fetch_array($res_area)) {
if(stripos(reset(explode("_", $row_state['area'])),'ma') !== FALSE)
{
$state_exp = reset(explode("_", $row_state['area']));
}
}

Related

search form php/sql multiple inputs

i've a problem with a search form. It works only if I use all the 4 fields, but if a leave a field empty the while loop echoes out all the table's records.
Can someone please help me?
This is my php code for the search function
<?php
if (isset($_POST['cerca'])){
$cerca_tt = $_POST['tt_carrier'];
$cerca_risorsa = $_POST['risorsa_cerca'];
$cerca_team = $_POST['team_cerca'];
$cerca_linea = $_POST['linea_cerca'];
$sql_cerca = "SELECT * FROM normal WHERE
tt LIKE '%".$cerca_tt."%'
OR risorsa LIKE '%".$cerca_risorsa."%'
OR team LIKE '%".$cerca_team."%'
OR linea LIKE '%".$cerca_linea."%'";
if($sql_cerca) {
$trovati = mysql_query($sql_cerca); ?>
if the POST is blank then the variable is blank thus everything will match like '%%'
for example if $cerca_tt is blank. your query would be
"SELECT * FROM normal WHERE tt like '%%'"
that matches everything.
create the query based on the POST response.
$sel = "SELECT * from normal";
//You will need to deal with the WHERE part of the query.
if (!empty($cerca_tt)){
$sel .= " OR tt like '%".$cerca_tt."'";
}
etc....///
If you only provide one search parameter and the rest are empty strings, which you wrap with %, you are effectively searching everything. You need to build up your query. For example (simple):
$sqlParts = [];
if(isset($_POST['tt_carrier'])) {
$sqlParts[] = "tt LIKE '%".$cerca_tt."%'";
}
if(isset($_POST['risorsa_cerca'])) {
$sqlParts[] = "risorsa LIKE '%".$cerca_risorsa."%'";
}
if(isset($_POST['team_cerca'])) {
$sqlParts[] = "team LIKE '%".$cerca_team."%'";
}
if(isset($_POST['team_cerca'])) {
$sqlParts[] = "linea LIKE '%".$linea_cerca."%'";
}
if(!empty($sqlParts)) {
$sql = "SELECT * FROM normal WHERE " . implode(' OR ', $sqlParts);
}

mySql - search query based on keywords

I wasn't able to find anything that really helped me out with this.
I have a database with the following structure:
and a simple query to search and display some results from the DB:
if ($_REQUEST['search']) {
$q = $_REQUEST['search'];
$q_comma = explode(", ", $q);
$where_in_set = '';
$count = count($q_comma);
foreach ($q_comma as $q) {
$counter++;
if ($counter == $count) {
$where_in_set .= "FIND_IN_SET('$q','keywords')";
} else {
$where_in_set .= "FIND_IN_SET('$q','keywords') AND ";
}
}
$sql_res = "select link, description, keyword from myDB where $where_in_set or description like '%$q%'";
This code works, but not really as I wanted.
In the keyword column, I have different comma separated keywords, and i'd like to be able to search for them even if the order is different.
Here's an example: Let's say I have into my keyword column
Google, Facebook, twitter
With my current code if I type Google, I can see the result, but if i type twitter, I don't see it.
Is there anything I can do to make it work without taking into account the order of the keywords, but having a pretty fast search as well?
Any help will be really appreciated.
PS. I'd like to keep only one DB if possible, cause I read about creating a new table with only ID and keywords, and on my search join the tables on the ID's, but I would prefer a better solution if possible.
Thanks
EDIT
Some updates:
as pointed out by #Frayne Konok, i have the query in lowcase and all the value in the db in lowcase as well, so case cannot be the problem
As suggested by #mkaatman, i wrapped keyword column around backticks (`)
I changed my query so that now it looks like the one suggested by #user2272989 in the answer
So my query now looks like this:
select link, description, keyword from myDB
where (FIND_IN_SET('google',`keyword`) or
FIND_IN_SET('facebook', `keyword`) or
FIND_IN_SET('twitter', `keyword`))
OR description like 'google, facebook, twitter'
And it is returning values even if the order is different, but it is not showing only the one i want.
For example, if i write twitter, google, facebook, i have as a return something like 28 rows, where only 2 have all of the three words as a keyword, while the other my have only one or two
EDIT 2 - Updates
I just want to "reopen" this question since I didn't manage to solve this. If I change all the keywords into an object, will then be better to use them as keywords? or what is the absolute best and more reliable way to search a database for keywords? Having different DBs and use an INNER JOIN?
At this point I'm willing to change the structure and the code if it helps.
Thanks
This may help you
$sql_res = "select link, description, keyword from myDB
where (FIND_IN_SET('yahoo',keyword) or
FIND_IN_SET('twitter',keyword)) or
description like '%$q%'";
You are using AND condition in FIND_IN_SET
I ended up using this structure and query here:
$q = $_REQUEST['search'];
$q_comma = array_filter(explode(' ', str_replace(',', ' ', $q)));
$count = count($q_comma);
$dbQuery = "select id, link, description, tags from db where ";
$searchTerms = '';
foreach ($q_comma as $q) {
$counter++;
if ($counter == 1) {
$searchTerms .= "tags LIKE '%$q%'";
} else {
$searchTerms .= "and tags LIKE '%$q%'";
}
}
$sql_res = $dbQuery . $searchTerms;
$result = mysqli_query($db, $sql_res) or die(mysqli_error($db));
$return_arr = array();
$data = array();
if (mysqli_num_rows($result) == 0) {
echo "Nothing";
} else {
while ($row = mysqli_fetch_object($result)) {
$data[] = $row;
}
mysqli_free_result($result);
echo json_encode($data);
}

mysql count occurrences of special character in a field

I am wanting to count all occurrences of the # symbol in a field and originally i thought LIKE '%#%' would be the way to go, but if the character appears in the field more than once it only counts it as one.
What other method are there that i could use that would count every occurrence?
Thanks.
EDIT
For anyone needing it, this is what i ended up using that works.
$count = 0;
$sql = mysql_query("SELECT LENGTH(field_name) - LENGTH(REPLACE(field_name,'#','')) AS 'occurs' FROM table_name WHERE field_name LIKE '%#%'");
while ($data = mysql_fetch_assoc($sql)) {
$count += $data['occurs'];
}
echo $count;
select length('aa:bb:cc:dd')-length(replace('aa:bb:cc:dd',':',''));
source: http://lists.mysql.com/mysql/215049
You could make this even simpler by using the ``substr_count function in php. see below.
$message = $row['themessage'];
echo substr_count($message, '#');
what this will return is the number of times # has occurred in your "themessage" field in your database.

PHP need help to filter a loggfile

So my problem is this I got a code that loops trough a loggfile then compares them to a treestructure and then gives them a id that correspond to the id in the structure. To not get a lot of bad traffic i sort out all the 302 and above.
The problem is now that i want some specific 302s to count that have a particular pagetype in the structure. This is not a big problem as I can just match the url in the loggfile against the url in the tree structure but some loggfiles does not use friendly url while the structure is in friendly url this creates a problem but I can just match the id in the query parameter with the id in the structure. I then make a string of all the ids that match the special pagetype that I want.
The problem is this I can not get the Mysql statement to work, it looks like this.
$sqlQ1 = "SELECT `lid` FROM logfile WHERE date = '$date' AND ´query´ IN '$check'";
A example query can look like this "id=4&epslanguage=sv" so I want to check only the id=X part.
It´s a kinda easy question really im just stuck and can not get it to work, any help is appreciated!
I think your Q is: How do I extract id from that part of a line?
".. so I want to check only the id=X part."
Once you have isolated that string then you can use:
$string = "id=4&abclang=sv";
parse_str($string);
echo $id; // 4
EDIT
In light of other responses:
$strings[] = "id=4&abclang=sv";
$strings[] = "id=45&abclang=en";
$vals = array();
foreach( $strings as $string){
parse_str($string);
$vals[] = $id ;
}
$in_clause = join(",", $vals) ;
$sql = "SELECT lid FROM logfile WHERE something IN ($in_clause) ";
echo $sql; // SELECT lid FROM logfile WHERE something IN (4,45)
So you have the IDs already and want to filter the MySQL query to just get these rows?
$check = Array(1, 2, 3, 4);
$check = implode(",", $check);
$sqlQ1 = "SELECT `lid` FROM logfile WHERE date = '$date' AND ´query´ IN ($check)";

Using a set of Mysql results as a comparison in PHP

This question is quite simple but I'm not sure of the terms involved to look up the answer myself. What I have is a MYSQL database containing all of my product information. I would like to make an image appear on the product pages for products that have a certain attribute. I have created this SQL query which outputs the list of product_ids for the products that I would like the image to show up on. However, I do not know how to use this set of results in the page itself.
I currently have:
$cupwinnerids = mysql_query("SELECT product_id FROM `jos_vm_product_type_1` WHERE jos_vm_product_type_1.Cup_Winner ='Cup Winners';");
while($row = mysql_fetch_array($cupwinnerids))
{
echo $row['product_id'] . ",";
}
This outputs the correct ids with a comma in between them. What I would like to do is wrap the whole thing with something like $listofids = (...) and then I can use in the product page PHP file: if $product_id is in $listofids then ... if not then ... I am just having a problem understanding how to use this selection of ids. If I try to output the list directly I just get "array". Any help would be greatly appreciated.
The problem may be that you are trying to display the array using echo, while you should use print_r.
In your case you could do something like this:
$listofids = array();
$cupwinnerids = mysql_query("SELECT product_id FROM `jos_vm_product_type_1` WHERE jos_vm_product_type_1.Cup_Winner ='Cup Winners';");
while($row = mysql_fetch_array($cupwinnerids))
{
array_push($listofids, $row['product_id']);
}
print_r($listofids);
As Ryan commented, if you want to manage the values of the array you should then use a foreach loop, that iterates through the array, something like this
foreach ($listofids as $id) {
echo $id . ", ";
}
// EDIT: you could also use echo implode($listofids,", ") which will do basically the same
If what you want is to compare if $product_id is in $listofids us in_array, that returns true if the value you are looking for is in the array, and false if it isn't:
if (in_array($product_id, $listofids)) {
echo "Product ID is in the List of Product ID's";
}
else {
echo "Product ID isn't in the List of Product ID's";
}
Why not return $cupwinnerids to your products page, and then do something like...
while($row = mysql_fetch_array($cupwinnerids)) {
if ($row['product_id'] == $product_id)
// display your image
}
It sounds like you would be better off modifying your query for returning the products so that it joins to the jos_vm_product_type_1 table -
SELECT `jos_vm_product`.*, IF(`jos_vm_product_type_1`.`product_id` IS NULL, 0, 1) AS `winner`
FROM `jos_vm_product`
LEFT JOIN `jos_vm_product_type_1`
ON `jos_vm_product`.`product_id` = `jos_vm_product_type_1`.`product_id`
AND `jos_vm_product_type_1`.`Cup_Winner` ='Cup Winners'

Categories