I have a MySQL field called "tags" an example result. The single field has a list of text with comma separated values.
A real example:
red, pants, shoes, heels, lookbook
I want to somehow use find and replace or implode feature to print out this row as separate links.
My guess so far:
<?php
$tag=$row["tags"];
whilst (!$tag=="") {
echo '$tag, "';
}
?>
split the comma separated list into an array using explode()
convert each element in the list to a link using foreach
convert the array to a comma separated list using implode()
example:
$tags = explode(", ", $row["tags"]);
foreach ($tags as &$tag) {
$tag = "$tag";
}
echo implode(", ", $tags);
Another approach would be using preg_replace:
$row['tags'] = "banana, apple, peach, strawberry";
echo preg_replace( '#([^,\s]+)#is',
'$1',
$row['tags']);
You should probably take a look at this answer first SQL Array Search (how to store such an information in the database). If you still want to use coma separated list, the best way is probably using explode(), array_map() and implode():
function generateLink( $tag){
$tag = htmlspecialchars( trim( $tag));
$str = "$tag";
}
$tags = explode( ',', $row['tags']);
$new_tags = array_map( 'generateLink', $tags);
echo implode( ', ', $new_tags);
// Of course you can chain it to:
echo implode( ', ', array_map( 'generateLink', explode( ',', $row['tags'])));
However if you use correct database design you should this SELECT (displaying one product):
SELECT tags.name
FROM tags_products
INNER JOIN tags ON tags_products.tag_id = tags.id
WHERE tags_products,product_id = ?
And with php:
$q = $db->query( 'mentioned select');
$result = array();
while( $row = $q->fetch_assoc()){
$result[] = genereateLink( $row['name']);
}
And in case of mass listing of product to increase performance use this select with GROUP_CONCAT:
SELECT products.id, products.name, GROUP_CONCAT(tags.name ASC SEPARATOR ', ') AS tags
FROM products
LEFT JOIN tags_products ON tags_producsts.product_id = products.id
INNER JOIN tags ON tags_products.tag_id = tags.id
GROUP BY products.id
And apply the first mentioned code on $row['tags'] :)
Related
I am trying to do a str_replace without success.. for some reason the data from MySql isn't working inside the str_replace function...
Code to bring all strings which will be used to replace the string:
$aspas = "'";
$sql2 = '
SELECT
GROUP_CONCAT(
DISTINCT CONCAT("'.$aspas.'", prefixo, "-'.$aspas.','.$aspas.'-", posfixo, "'.$aspas.'")
) AS prefixo_posfixo
FROM
profissionais
';
$stm2 = $pdo->prepare($sql2);
$stm2->execute();
$resultado = $stm2->fetch();
Produces with no error this output:
echo $resultado[0] >> 'dr-','-advogado','dra-','-advogada'
But when I try to insert inside the str_replace function :
$newstring = str_replace([$resultado[0]], '', 'dra-flavia-barao-advogada');
echo newstring >> dra-flavia-barao-advogada
As you see, the result keep the same, it doesn't replace the string ;(
I think it is something about convert the array to string, but the $resultado[0] isn't in a array format so I cant implode...
Do you know what I am doing wrong?
I forgot to post the solution before, There is:
//SELECT THE STRINGS TO BE USED TO REMOVE FUNCTION
$sql2 = '
SELECT
GROUP_CONCAT(
DISTINCT CONCAT(prefixo, "-,-",posfixo)
) AS prefixo_posfixo
FROM
profissionais
';
$stm2 = $pdo->prepare($sql2);
$stm2->execute();
$prefixo_posfixo = $stm2->fetch();
//REPLACE / REMOVE THE STRINGS
$newstring = str_replace(explode(",", $prefixo_posfixo[0]), '', 'dra-flavia-barao-advogada');
//PRODUCES THE OUTPUT
flavia-barao
I have a form which is a select multiple input which POSTs values like this: option1,option2,option3 etc..
How is the best way to convert this to 'option1','option2','option3' etc...
Currenty I'm doing this, but it feels wrong??
$variable=explode(",", $variable);
$variable=implode("','", $variable);
The reason why I'm doing this is because I want to use the form select multiple inputs in a SQL Query using IN.
SELECT * FROM TABLE WHERE some_column IN ('$variable')
You can wrap whatever code in a function to make the "feels wrong" feeling disapear. E.g.:
function buildSqlInClauseFromCsv($csv)
{
return "in ('" . str_replace(",", "','", $csv) . "') ";
}
If $variable = "option1,option2,option3"
you can use:
"SELECT * FROM TABLE WHERE FIND_IN_SET(some_column, '$variable')"
Here is what I used:
WHERE column IN ('".str_replace(",", "','", $_GET[stringlist])."')
we know that implode converts array to string,we need to provide the separator and then array as shown below, here we have (coma ,) as a separator.
Implode breaks each element of an array with the given separator,I have conceited '(single quotes) with the separator.
$arr = array();
$arr[] = "raam";
$arr[] = "laxman";
$arr[] = "Bharat";
$arr[] = "Arjun";
$arr[] = "Dhavel";
var_dump($arr);
$str = "'".implode("','", $arr)."'";
echo $str;
output: 'raam','laxman','Bharat','Arjun','Dhavel'
There is only one correct way to escape strings for SQL - use the function provided by the database api to escape strings for SQL. While mysyl_* provides mysql_real_escape_string():
$choices = explode(",", $variable);
foreach($choices as &$choice)
$choice = "'".mysql_real_escape_string($choice)."'";
$choices = implode(",", $choices);
PDO provides a method that will add quotes at the same time:
$choices = explode(",", $variable);
foreach($choices as &$choice)
$choice = $pdoDb->quote($choice);
$choices = implode(",", $choices);
Note that PDO::prepare doesn't really work here
Users writing an article have the option to write some tags, tags are written like this:
tag1, tag2, tag3
So tags are stored like: $tags = "tag1, tag2, tag3";
I want to make sure, every tag has a minimum of 3 characters, so i need to validate the tags.
I have tried this:
$tagsstring = explode(",", $tags);
$tagslength = array_map('strlen', $tagsstring);
if (min($tagslength) < 3) {
echo "Error... Each tag has to be at least 3 characters.";
}
It seems to work, sometimes... But of you write:
tag1, df
It wont give an error.
Any suggestions?
$tagsstring = explode(",", $tags);
$trimmedtags = array_map('trim', $tagsstring);
$tagslength = array_map('strlen', $trimmedtags);
if (min($tagslength) < 3) {
echo "Error... Each tag has to be at least 3 characters.";
}
use this version it trims your strings before calcutlating the length.
The issue is that by exploding on a bare comma on input such as tag1, df you make the resulting array be ['tag1', ' df'] -- the second string actually has a length of 3.
The are two approaches to fix this that spring to mind:
Simply array_map with trim before calculating the lengths:
$tagsstring = explode(",", $tags);
$tagsstring = array_map('trim', $tagsstring);
$tagsstring = array_map('strlen', $tagsstring);
Use a regular expression and preg_split to do the splitting:
$tagsstring = preg_split("/\s*,\s*/", $tags);
$tagsstring = array_map('strlen', $tagsstring);
See it in action.
If i understand you correctly you said you want make sure I want to make sure, every tag has a minimum of 3 characters
if you are only worried about alphabetical charters then its a different game that means
tab1 is valid
tab200 is valid
t299 not valid
ta444 not valid
If this what you want then you can use this
$tags = "tag1, tag2, ta11 ,tag3 , df ";
$tags = explode ( ",", $tags );
function checker($tag) {
preg_match_all ( '/[a-zA-Z]/u', $tag, $matches );
return count ( $matches [0] );
}
foreach ( $tags as $tag ) {
if (checker ( $tag ) < 3) {
echo "Error... Each tag ($tag) has to be at least 3 characters.\n";
}
}
Output
Error... Each tag ( ta11 ) has to be at least 3 characters.
Error... Each tag ( df ) has to be at least 3 characters.
I am trying to print the different category's selected in a single line in xml,
like
<cat_name>meeting, food and drinks, sports</cat_name>
The output I am getting:
<cat_name>meeting, food and drinks, sports,</cat_name>
I want to remove only the last comma.
The code I have written so far is:
$sq="
select category_main.cat_name
from category_main
join category
on(category.cat_id=category_main.cat_id)
where category.event_id='$event_id'
";
$e=mysql_query($sq);
$xml ='<cat_name>';
while($row=mysql_fetch_array($e))
{
$res=$row['cat_name'];
//$new = substr($val,0,-1);
$xml .="$res, ";
}
$xml .='</cat_name>';
echo $xml;
Call trim() with the optional second parameter as a ','
trim($cat_name, ',')
However, since you're doing this in a while loop, you should build an array then implode() it rather than building the string in the loop. This avoids the extra comma to begin with.
$arr = array();
while($row=mysql_fetch_array($e))
{
$arr[] = $row['cat_name'];
}
$cat_name = implode(",", $arr);
// $cat_name is now "meeting, food and drinks, sports"
You can do this by [i used my variable]
$str = substr($str,0, (strlen($str)-1));
Or use a rtrim, rtrim( $cat , ',' ) http://php.net/rtrim
The search query is:
"product1 prod2 prod4"
I need to make the mysql
SELECT *
FROM tableprod
WHERE (prod LIKE '%product1%'
AND prod LIKE '%prod2%'
AND prod LIKE '%prod4%')
using the mysql_real_escape_string for the input query...
Simple string manipulation:
$terms = explode(' ', $search);
$bits = array();
foreach ($terms as $term) {
$bits[] = "prod LIKE '%".mysql_real_escape_string($term)."%'";
}
$query = "SELECT * FROM tableprod WHERE (".implode(' AND ', $bits).")";
If you can meet the constraints, you migh be better off just using a FULLTEXT index which would save you the trouble of having to split the string, plus you'd get the bonus of being able to use basic boolean operators for the search (and/or/not)
without a loop(i've always tried to avoid loops):
$str = "product1 prod2 prod4";
$sql = "select * from tableprod where (prod like '%" . str_replace( ' ', '%\' AND prod LIKE \'%', $str ) . '%\')';
if it's possible you will have more than one space inbetween items use preg_replace