Fetch mysql data with different operators - php

Is it possible to fetch data from a database adding a dot into it using MySQL?
e.g. If I've data inserted into a DB such as 'BA', after fetching the value can I display it as B.A?
Can I also change something from L_T to something like L/T?
Thanks

In case of BA to B.A do something like this:
SELECT LEFT(YOURCOLUMN, 1) + '.' + RIGHT(YOURCOLUMN, 1) FROM YOURTABLE
And for the other one I will let you guess :)

For the second part use
SELECT REPLACE(YOURCOLUMN, '_', '/') AS YOURCOLUMN
This will replace any instance of _ with / in results for the selected column. If you exclude the AS YOURCOLUMN the row name in the results would be replace(YOURCOLUMN, '_', '/')

You can do this by using php
$db_cecord = "BA";
$formatted = implode('.',str_split($db_record));
This will result in B.A

Related

Create an ID based on integer with letter

I have a database containing messages with an "id" column in integer auto increment. Classical. But I would like to create a "visual" id based on this integer id. This is what I want :
A0001
A0002
[...]
A9999
B0001
B0002
[etc]
The ideal would be to generate automatically (in MYSQL) this messageId based on the integer id. I can also generate this id in PHP. But how ? The difficulty is that we have to check the last id in database to calculate what letter prefix the visual id.
Can you help me to generate this ? In MYSQL if it possible directly or in PHP?
You could use the following, but it is only good for numbers from 0 to 249999 (A0000 - Z9999)
select concat(char(ord('A')+round(ID / 10000)),ID % 10000) from ...
To convert back from a visual ID you can use the following:
select ord(VISUAL_ID)-ord('A')+mid(VISUAL_ID,2)
have you considered using hex? Why not to write OxA001 it's still integer if you do A001 then it's string and no AUTO INCREMENT is possible.
But if you want really to do it in mysql the only way would be using TRIGGERS.
You have 2 options you can create insert AFTER or BEFORE Insert statement and in this trigger you should update the value of ID to your value based on previous row. But I really recomend using hex.
You can read more about triggers here
You can create such ids using a before insert trigger to create the new value.
Basically you would look up the maximum value and then increment it, by doing something like:
(case when maxvalue like '%9999'
then concat(char(ascii(left(maxvalue, 1) + 1)), '0000')
else concat(left(maxvalue, 1), lpad(right(maxvalue, 4) + 1), 4, '0')
end);
However, I would discourage you from doing this and just set up a regular auto-increment column.
try this it may help you.
for ($i = 'A'; $i != 'AA'; $i++)
{
$prefix = $i;
$id = $prefix.sprintf("%03s",$suffix);
for ($j=1;$j<=5;$j++)
{
$res = "$id"."$j";
echo "$res"."<br>";
}
}

MySql Search With Special Character

I searching records from database using MySql as -
SELECT * FROM tab WHERE col LIKE '%myvalue%';
This is working fine and showing all the records having myvalue.
Now the problem is i have some records like my'value, myva'lue, myval-ue and my-value And also want to include these records in search. Also when i search for my'value then it should show myvalue and my-value.
How to achieve this? Any Help. Is it possible to do using LIKE operator?
As you are using PHP you should do the following, if someone uses your search:
Get the search-term via $_POST
Remove all special characters from the search-term (my'value becomes myvalue)
Replace the search term with MySQL wildcards (myvalue becomes %m%y%v%a%l%u%e%)
Execute SELECT * FROM tab WHERE col LIKE '%m%y%v%a%l%u%e%'
Any of the other solutions will not match all your requirements.
SQL Fiddle: http://sqlfiddle.com/#!2/20f811/2
Use
SELECT * FROM tab WHERE col LIKE '%myvalue%' OR col LIKE '%my_value%'
The underscore _ is a single character wildcard.
How about this?
SELECT * FROM tab WHERE col LIKE 'my%' OR col LIKE '%value'
this will check col should start with my and end with value.
Demo
Edit 1
As there can be any special character and regexp don't work with MySQL, I would suggest you to do what you want to achieve in PHP by replacing special character by null and then matching the string with myvalue.
Hope this helps you.
Edit 2
I don't know php exactly, but can tell you what to do little bit.
mysql = "SELECT id, col FROM tab WHERE col LIKE '%my%' OR col LIKE '%value%'";
rs = mysql.execute();
String newString = "";
while (rs.next()) {
newString = rs.getString(2);
newString = new string after replacing special characters using regexp
if (newString.equals("myvalue")) {
// your code here..... this is place what you wanted.
}
}
Got this...
PHP Part
$term = str_replace('-','',str_replace(',', '', str_replace('\'', '', $term)));
MySql Part
SELECT *
FROM tab
WHERE ((REPLACE(REPLACE(REPLACE(col, '\'', ''), ',', ''), '-', '') LIKE "%$term%")
OR (col LIKE "%$term%"));
See this demo.

MySQL query for content UP TO a certain string and AFTER same string

In a query result, I want to store everything leading UP TO a certain string, the </a> in and then everything AFTER the </a> to a second variable.
[edit] a rephrasing of the question:
the value in $row[post_content] would be something like "<ahref=''><image></a><p>copy</p>" ...
i need to split this into $val1 = "<ahref=''><image></a>"; and $val2 = "<p>copy</p>";
This is probably done with substr()? but i have no idea how, and I HAVE searched, and found nothing but references to bad character sets in mysql because of my use of the term 'character' in my search.
This will do it, assuming val is your column name:
select
substr(val, 1, instr(val, '</a>') + length('</a>') - 1) as part1,
substr(val, instr(val, '</a>') + length('</a>')) as part2;
Here's a test:
set #val := 'onetwothree';
select
substr(#val, 1, instr(#val, '</a>') + length('</a>') - 1) as part1,
substr(#val, instr(#val, '</a>') + length('</a>')) as part2;
$tmp = explode('</a>', $yourStr);
print_r($tmp);
You tagged your question with mysql, so Bohemian gave you answer using mysql. Please use correct tags and description to get right answer.

How to check if a string already exists in mysql (All word order options)?

Let's say i check if
$strig = "how can i do this";
already exists in my database with all words order options?
Like:
"how i can do this"
or
"i do this can how"
...
...
my database looks like:
id string
1 how can i do this
2 hello how are you
3 how i can do this world
4 another title
etc etc
Thanks
The number of possible combinations is n! (120 in your sample) so checking if this string already exists is quite complex task.
I would recommend to use the following algorithm:
Add new column StringHash to your table
On insert order your string (e.g. alphabetically), calculate its hash and store in StringHash:
"how can i do this" => "can do how i this" => md5("can+do+how+i+this")
If you want to check if a certain string exists in the db then again calculate its hash as described above and query the db on YourTable.StringHash
This is a tricky problem if you want to fix this in sql only, but that aside:
As #er.anuragjain says, you can do a query with LIKE %word%, but you would also get a hit on your example '3'.
So if you have a query like this:
SELECT * FROM table WHERE
column LIKE '%how%'
AND column LIKE '%can%'
AND column LIKE '%i%'
AND column LIKE '%do%'
AND column LIKE '%this%'
Then you also get number 3. So you need to check if there are no other words. You can do this by checking the word count (if you have 5 words and all of your words are in there, you are done.).
Checking wordcount is not trivial, but there is a trick. From several sources*:
SELECT LENGTH(total_words) - LENGTH(REPLACE(total_words, ' ', ''))+1
FROM tbl_test;
should do the trick. So check the LIKE's, and check the wordcount, and you're done. But I'm not really sure this is a pretty sollution :)
http://www.webtechquery.com/index.php/2010/03/count-number-of-words-in-mysql-mysql-words-count/
and http://www.mwasif.com/2008/12/count-number-of-words-in-a-mysql-column/
(random google hits :) )
you can ask if the string where you are searching in, contains: "how" and "can" and "I" and "do" and "this"
something like this:(I don't know the syntax in mysql but see the concept)
if(string.contain("how")&&
string.contain("can")&&
string.contain("I")&&
string.contain("do")&&
string.contain("this"))
{
//you find the string
}
If you are using mysql then try this..
select * from tablename where columnname Like '%how%' AND columnname LIKE '%can%' AND columnname LIKE '%I'% AND columnname LIKE '%DO'% AND columnname LIKE '%This'%;
Here if u have dynamic value in $string then first convert it into an array spliting by space.then create a $condition varriable from the array and append that in select * from tablename where and run that query.
thanks
should be the wildcard call in mysql
select * From tablename Where columnname LIKE '%how%'
you can use regex first crate a function like this
public function part($str){
$str = str_replace('‌',' ',$str);
$arr = explode(' ',$str);
$rejex = '';
foreach($arr as $item){
$rejex .= "(?=.*$item)";
}
return $rejex;
}
and then use sql regex
$sql = "SELECT * FROM `table` WHERE `column` REGEXP ".part($str);

Remove values in comma separated list from database

I have a table in my MySQL database called 'children'. In that table is a row called 'wishes' (a comma separated list of the child's wishlist items). I need to be able to update that list so that it only removes one value. i.e. the list = Size 12 regular jeans, Surfboard, Red Sox Baseball Cap; I want to remove Surfboard.
My query right now looks like this
$select = mysql_query('SELECT * FROM children WHERE caseNumber="'.$caseNum.'" LIMIT 1 ');
$row = mysql_fetch_array($select);
foreach ($wish as $w) {
$allWishes = $row['wishes'];
$newWishes = str_replace($w, '', $allWishes);
$update = mysql_query("UPDATE children SET wishes='$newWishes' WHERE caseNum='".$caseNum."'");
}
But the UPDATE query isn't removing anything. How can I do what I need?
Using these user-defined REGEXP_REPLACE() functions, you may be able to replace it with an empty string:
UPDATE children SET wishes = REGEXP_REPLACE(wishes, '(,(\s)?)?Surfboard', '') WHERE caseNum='whatever';
Unfortunately, you cannot just use plain old REPLACE() because you don't know where in the string 'Surfboard' appears. In fact, the regex above would probably need additional tweaking if 'Surfboard' occurs at the beginning or end.
Perhaps you could trim off leading and trailing commas left over like this:
UPDATE children SET wishes = TRIM(BOTH ',' FROM REGEXP_REPLACE(wishes, '(,(\s)?)?Surfboard', '')) WHERE caseNum='whatever';
So what's going on here? The regex removes 'Surfboard' plus an optional comma & space before it. Then the surrounding TRIM() function eliminates a possible leading comma in case 'Surfboard' occurred at the beginning of the string. That could probably be handled by the regex as well, but frankly, I'm too tired to puzzle it out.
Note, I've never used these myself and cannot vouch for their effectiveness or robustness, but it is a place to start. And, as others are mentioning in the comments, you really should have these in a normalized wishlist table, rather than as a comma-separated string.
Update
Thinking about this more, I'm more partial to just forcing the use of built-in REPLACE() and then cleaning out the extra comma where you may get two commas in a row. This is looking for two commas side by side, as though there had been no spaces separating your original list items. If the items had been separated by commas and spaces, change ',,' to ', ,' in the outer REPLACE() call.
UPDATE children SET wishes = TRIM(BOTH ',' FROM REPLACE(REPLACE(wishes, 'Surfboard', ''), ',,', ',')) WHERE caseNum='whatever';
Not exactly a direct answer to your question, but like Daren says it's be better having wishes as its own table. Maybe you could change your database schema so you have 3 tables, for instance:
children
-> caseNum
-> childName
wishes
-> caseNum
-> wishId
-> wishName
childrensWishes
-> caseNum
-> wishId
Then to add or delete a wish for a child, you just add or delete the relevant row from childrensWishes. Your current design makes it difficult to manipulate (as you're finding), plus leaves you at risk for inconsistent data.
As a more direct answer, you could fix your current way by getting the list of wishes, explode() 'ing them, removing the one you don't want from the array and implode() 'ing it back to a string to update the database.
Make wishes table have this format:
caseNumber,wish
Then you get all of a child's wishes like this:
SELECT * FROM children c left join wishes w on c.caseNumber = w.caseNumber WHERE c.caseNumber= ?
Removing a wish becomes:
DELETE from wishes where caseNumber = ?
Adding a wish becomes:
INSERT into wishes (caseNumber,wish) values (?,?)
Returning one wish becomes:
SELECT * FROM children c left join wishes w on c.caseNumber = w.caseNumber WHERE c.caseNumber= ? LIMIT 1
Having the wishes indexed in an array which is thereafter serialized could be an idea, otherwise you would need to retrieve the string, slice it, remove the part you don't want, then concatenate the remains. This can be done by using the explode() function.
If you were to use an array, you would retrieve the array and then sort through it with a loop like this:
// Wishes array:
// Array (
// [0] Regular Jeans
// [1] Surfboard
// [2] Red Sox Baseball Cap
// )
$wishes = $row['wishes']; // This is a serialized array taken from the database
$wishes = unserialize($wishes);
foreach ($wishes as $key => $value) {
if ($value == 'Surfboard') {
unset($wishes[$key]);
break;
}
}
$wishes = serialize($wishes);
// Update database
Keep in mind that index [1] now won't exist in the array, so if you wish to have a clean array you should loop through the array and make it create a new array by itself:
foreach ($wishes as $wishes) {
$newArray[] = $wishes;
}
I think the best answer to such issue is here
The best way to remove value from SET field?
query should be like this which covers the ,value or value, or only value in the comma separated column
UPDATE yourtable
SET
categories =
TRIM(BOTH ',' FROM
REPLACE(
REPLACE(CONCAT(',',REPLACE(col, ',', ',,'), ','),',2,', ''), ',,', ',')
)
WHERE
FIND_IN_SET('2', categories)
Here you can have your condition in where clause. for more details refer above link.
You can create function like this:
CREATE FUNCTION `remove_from_set`(v int,lst longtext) RETURNS longtext CHARSET utf8
BEGIN
set #lst=REPLACE(#lst, ',,', ',');
set #lng=LENGTH(#lst) - LENGTH(REPLACE(#lst, ',', ''))+1;
set #p=find_in_set(#v,#lst);
set #l=SUBSTRING_INDEX( #lst, ',', #p-1);
set #r=SUBSTRING_INDEX( #lst, ',', #p-#lng);
IF #l!='' AND #r!='' THEN
return CONCAT(#l,',',#r);
ELSE
RETURN CONCAT(#l,'',#r);
END IF;
END
Using:
SELECT remove_from_set('1,,2,3,4,5,6',1)

Categories