Removing empty spaces and BR from string in echo - php

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

Related

Is there a way to use SQL query that would return results if values can be in any order?

My code let me perform search, as long as the order of the words is correct.
Let's say I'm searching for big dog, but I also want to search for dog big. It get more complicated with 3 or more words.
Is there a way to create a SQL query which would let me search through values with any order?
Only way I can think of this is by having multiple queries, where I change order of PHP variables manually...
<?php
if(isset($_GET['query']) && !empty($_GET['query'])) {
$query = $_GET['query'];
$query_array = explode(' ', $query);
$query_string = '';
$query_counter = 1;
foreach($query_array as $word) {
$query_string .= '%' . $word . (count($query_string) == $query_counter++ ? '%' : '');
}
$query = "SELECT * FROM pages WHERE Name LIKE '$query_string'";
$result = sqlsrv_query($cms->conn, $query);
while($row = sqlsrv_fetch_array($result)) {
extract($row);
echo ''.$Name.'<br>';
}
sqlsrv_free_stmt($stmt);
}
else {
//echo 'NO GET';
}
?>
You could assemble your conditions and check for each word on it's own:
$query_array = explode(' ', $query);
$queryParts = array();
foreach ($query_arra AS $value){
$queryParts[]="Name like '%".mysql_real_escape_string($value)."%'";
}
$searchString = implode(" AND ", $queryParts);
The Search string would now be Name like '%big%' AND Name like '%dog%' ... depending on how much search-keywords have been there.
I use the same approach very often, also when it is required that ALL keywords appear in at least ONE of the columns. Then you need one more loop to create the required AND conditions:
$search = "Big Dog";
$keywords = explode (" ", $search);
$columns = array("Name", "description");
$andParts = array();
foreach ($keywords AS $keyword){
$orParts = array();
foreach($columns AS $column){
$orParts[] = $column . " LIKE '%" . mysql_real_escape_string($keyword) . "%'";
}
$andParts[]= "(" . implode($orParts, " OR ") . ")";
}
$and = implode ($andParts, " AND ");
echo $and;
this would produce the query part (Name like '%Big%' OR description like '%Big%') AND (Name like '%Dog%' or description like '%Dog%')
So, it will find any row, where dog and big are appearing in at least one of the columns name or description (could also be both in one column)
Since your original querystring is something like %big%dog%, so I assume you are okay with matching big wild dog. In this case, you can just use the AND operator.
(Name LIKE '%big%" and Name LIKE '%dog%")
myisam supports full text search:
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
One thing you could look into is Full Text Search for ms sql server.
https://msdn.microsoft.com/en-us/library/ms142571.aspx
it's similar to a "search engine" in that it works off of an algorithm to rank results and even similar words (think thesaurus type lookups)
It's not exactly trivial to set up, but it's easy enough to find a tutorial on the subject and how to query from FTS (as the syntax is different than say LIKE '%big%dog%')
Here's a sample query from the page linked above:
SELECT product_id
FROM products
WHERE CONTAINS(product_description, ”Snap Happy 100EZ” OR FORMSOF(THESAURUS,’Snap Happy’) OR ‘100EZ’)
AND product_cost < 200 ;

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

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

How to make PHP makes this query

As I am learning PHP, naturally, I decided to create a search feature on my webpage. However I wanted to make mine more unique, so rather than using just a simple html input field as the 'search' field, I created two html select tags which allow the user to select two options and search based upon that. I managed to get the php to generate the search query, however it wasn't the sql query I wanted. My php code managed to generate a query hat looked like this: .com/results.php?option1=london&option2=car whereas ideally I want it to generate something like this: .com/results.php?combinedoptions=london+car
I've researched thoroughly into this and I hate to ask, what may be, a very simple question on this site.
$input = $_GET['input'];
$topic = $_GET['topic'];
$location = $_GET['location'];
$combined = $input . $topic . '' . $location;
$terms = explode(" ", $combined);
$query = "SELECT * FROM search WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%'";
else
$query .= "OR keywords LIKE '%$each%'";
}
You would just split the incoming string. Here's a piece of code:
<?php
$combinedoptions = 'london+car';
$array = explode("+", $combinedoptions);
if (sizeof($array) != 2) { /*problem here*/ echo 'bad parameters'; return; }
$option1 = $array[0];
$option2 = $array[1];
?>
Just using the explode() method. Compiled code.

conditional arrays

I'm trying to code an array that displays a certain set of products depending on the gender of the logged in user. The arrays not really the problem but the parts where I'm going to have to check the database then create the conditional statement from the results is the main problem i think.
Here is my code:
<?php
include"config.php" or die "cannot connect to server";
$gender=$_POST['gender'];
$qry ="SELECT * FROM server WHERE gender ='$gender'";
$result = mysql_query($qry);
$productdetails;
$productdetails1["Product1"] = "£8";
$productdetails1["Product2"] = "£6";
$productdetails1["Product3"] = "£5";
$productdetails1["Product4"] = "£6";
$productdetails1["Product5"] = "£4";
$productdetails2["Product6"] = "£8";
$productdetails2["Product7"] = "£6";
$productdetails2["Product8"] = "£5";
$productdetails2["Product9"] = "£6";
$productdetails2["Product10"] = "£4";
if (mysql_num_rows($result) = 1) {
foreach( $productdetails1 as $key => $value){
echo "Product: $key, Price: $value <br />";
}
}
else {
foreach( $productdetails2 as $key => $value) {
echo "Product: $key, Price: $value <br />";
}
}
?>
You if statement is wrong. = is an assignment operator, you should use a comparison operator like == or ===
What happens with the current code?
Some tips:
First try echoing $gender, to make sure it is getting through. It is submitted through post, what happens if nothing is being posted? Where is this coming from? You should try to use get instead. This seems like something you'd give someone a link to therefore post doesn't make sense here. You could always have both, and just get post if it exists otherwise use get otherwise default to 'male' or 'female' depending on your audience.
Next, what is your query outputting? It might be empty at this point if gender is not giving anything back. It seems like you are querying for all rows where gender = whatever was passed, but then your if statement is asking was there anything returned? Then all you are doing is going to the arrays, but you shouldn't be doing that you should be outputting what you got from the DB. Assuming you do actually have products in the table called server you should do something like this:
$products = mysql_query("SELECT * FROM server WHERE gender ='$gender");
while($product = mysql_fetch_array($products)){
echo $product['name'] . " " . $product['price']. " " . $product['gender'];
echo "<br />";
}
On that note. You should really call your table something else, like product not just "server" unless by server you mean a table filled with instances of waiters or computer hardware.

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