So I have a 625 digit long number to store in MySQL containing only 0 1 and 2 digits. The best way I've found to store it so far is as VARCHAR(625). I suspect that there are better ways to do it, I'm just not sure how.
I want to run a query such as "change the 128th character of the text to 1" without having to query the text into PHP, change it from there, and write the new text into the DB.
So the question is: what's the simplest method of doing this, and what field type is optimal for this kind of stuff?
Thanks in advance.
If you're going to be doing things like "change the 128th character of the text to 1" then I'd recommend keeping the data type as VARCHAR(625). If the length will always be 625 then you could use CHAR.
This will change the 128th character to 1 in MySQL:
UPDATE your_table set your_column =
CONCAT(SUBSTRING(your_column, 1, 127), '1', SUBSTRING(your_column, 129))
You can user INSERT() String function
give it a try
UPDATE tbl set field = INSERT(field,128,1,'1') where id = primary key
If you're only storing numbers, why not use int(625) instead of varchar?
You can use a replace command, but you'll have to know what to replace with
update TABLE_NAME set FIELD_NAME = replace(FIELD_NAME, ‘find this string’, ‘replace found string with this string’);
If you don't know what exactly you're replace with, you can replace the "replace found string with this string" with a sub query. Using length and substr to split, replace what you want, and concat back together.
This example should make what I'm saying make more sense
http://sqlfiddle.com/#!2/dbc21/2/0quey
A complex alternative:
Replacing 5th character to 'r' where primary key is 30:
update `myTable` set `myField`= regexp_replace(`myField`, '.', 'r', 5, 1) where `id`=30 limit 1
Related
I'm trying to figure out a safe way (if possible) to take the "url" column and copy it into the "company" column ... but I don't just want to copy the whole thing - let me try to explain.
I want to copy the company name like for example: apple, mircosoft..etc (from the path) and place them into their company column (to the left). I have about 5000+ results that need to be done and done safety. They all have the same file path structure with "../../images...."
Could I use something like UPDATE with SET?
UPDATE table SET company = url
Thanks for an feedback! I really appreciate it!
You can pick out the N left-most "fields" in a string separated by a character of your choice.
SELECT SUBSTRING_INDEX(url, '/', 4)
FROM mytable
LIMIT 10;
Returns:
../../images/apple
etc.
Then use a -1 to get the right-most field of that result to get the last one.
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(url, '/', 4), '/', -1)
FROM mytable
LIMIT 10;
Returns:
apple
Once you are happy with the expression, use it in an UPDATE:
UPDATE mytable SET company =
SUBSTRING_INDEX(SUBSTRING_INDEX(url, '/', 4), '/', -1);
See https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_substring-index
In mysql 8 you can use the regexp_substr function to use a regular expression to find a substring. Something like:
SELECT REGEXP_SUBSTR(url, '[^/]+', 14) FROM table;
Which would find any character that is not a / but starting at character 14 (part right after your leading ../../...etc string.
I'm working on a project using the pages in php / mysql and html; I have a table that contains the data for calls made from a PBX and save the number called, the source, date, time, etc ... what I want to do is to search within this table all the phone numbers that have the first 4 digits equal to those that pass through the query, only that i have no idea how to pull off only the 4-digit or at least how to make a control character by character of the value contained in the field. I tell you now that the field is a varchar. Thank you in advance :)
To do that in MySQL query, either
SELECT *
FROM <tablename>
WHERE LEFT(<column>, 4) = "<4 digits>"
or
SELECT *
FROM <tablename>
WHERE <column> LIKE "<4 digits>%"
or in the PHP side :
if (strpos($column,'<4 digit>') !== false) {
echo 'true';
}
Use this, to get substring
SELECT aut_name,
RIGHT(aut_name,7)
FROM author
WHERE country='UK';
See more at: http://www.w3resource.com/mysql/string-functions/mysql-right-function.php#sthash.xKNwZeki.dpuf
I suggest this solution:
$variableWhereYoustoreTheFourDigits="1234"; //Use whatever you have in your code to set the value.
$result =$mysqli->query("SELECT number FROM yourtable where number LIKE \"$variableWhereYoustoreTheFourDigits%\");
trim() is used to clear all the whitespaces. Now, instead of clearing white spaces, I want to eleminate all special characters from the 'username'. Is there any function like trim() for eliminating special characters??
My sql query is like
Select value from table_name where trim(username) = 'ABCD'
and it returns null value. But there are some values related to 'ABCD' and it displays all the entries when i execute the query
select value from table_name where username like '%ABCD%'
there are nothing else like visible in 'username' field. Is there any solution for this?
MySQL does not have such kind of functionality to remove special characters. Instead you can use replace function (if you know what are special characters).
replace("your column name",'_','')
See example :
Select value from table_name where REPLACE(trim(username$),"$","");
this if you want to replace the $ with an empty char
Try this function:
Create Function [dbo].[RemoveNonAlphaCharacters](#Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin
Declare #KeepValues as varchar(50)
Set #KeepValues = '%[^a-z]%'
While PatIndex(#KeepValues, #Temp) > 0
Set #Temp = Stuff(#Temp, PatIndex(#KeepValues, #Temp), 1, '')
Return #Temp
End
Call it like this:
Select dbo.RemoveNonAlphaCharacters('abc1234def5678ghi90jkl')
Once you understand the code, you should see that it is relatively simple to change it to remove other characters, too. You could even make this dynamic enough to pass in your search pattern.
refer this link:https://stackoverflow.com/a/22684392/3242978
i am using mysqlclient,
in one of my query, as shown below
sprintf (query, "select user from pcloud_session where id = '%s'", sid);
here some time this sid is with % sign in it like the example
2Cq%yo4i-ZrizGGQGQ71eJQ0
but when there is this % this query always fail, i think i have to escape this %, but how ?
i tried with \ and %% , but both of this not working, please help me here
UPDATE:
When using session.hash_bits_per_character = 6, in php session ,the default charset contains a character (comma) that will always be urlencoded(here it is %2C). This results in cookie values having this %2C in it, but session db having a comma instead of it. any idea about fixing this problem ?.. sorry for the confusion
Thanks
There's no need to escape a literal '%' in MySQL query text.
When you say the query "always fail", is it the call to the mysql_query function that is returning an error? Does it return a SQL Exception code, or is it just not returning the resultset (row) you expect?
For debugging, I suggest you echo out the contents of the query string, after the call to sprintf. We'd expect the contents of the string to be:
select user from pcloud_session where id = '2Cq%yo4i-ZrizGGQGQ71eJQ0'
And I don't see anything wrong with that SQL construct (assuming the id column exists in pcloud_session and is of character datatype. Even if id was defined as an integer type, that statement wouldn't normally throw an exception, the string literal would just be interpreted as integer value of 2.)
There should be no problem including a '%' literal into the target format of an sprintf. And there should be no problem including a '%' literal within MySQL query text.
(I'm assuming, of course, that sid is populated by a call to mysql_real_escape_string function.)
Again, I suggest you echo out the contents of query, following the call to sprintf. I also suggest you ensure that no other code is mucking with the contents of that string, and that is the actual string being passed as an argument to mysql_query function. (If you are using the mysql_real_query function, then make sure you are passing the correct length.)
UPDATE
Oxi said: "It does not return a SQL Exception code, it just does not return the result[set] I expect. I did print the query, it prints with % in it."
#Oxi
Here's a whole bunch of questions that might help you track down the problem.
Have you run a test of that query text from the mysql command line client, and does that return the row(s) you expect?
Is that id column defined as VARCHAR (or CHAR) with a length of (at least) 24 characters? Is the collation on the column set as case insensitive, or is it case sensitive?
show create table pcloud_session ;
(I don't see any characters in there that would cause a problem with characterset translation, although that could be a source of a problem, if your application is not matching the database charactarset encoding.)
Have you tested queries using a LIKE predicate against that id column?
SELECT id, user FROM pcloud_session WHERE id LIKE '2Cq\%yo4i-%' ESCAPE '\\'
ORDER BY id LIMIT 10 ;
SELECT id, user FROM pcloud_session WHERE id LIKE '2Cq%'
ORDER BY id LIMIT 10 ;
Are you getting no rows returned when you expect one row? Are you getting too many rows returned, or are you getting a different row than the one you expect?
That is an oddball value for an id column. At first, it looks almost as if the value is represented in a base-64 encoding, but it's not any standard encoding, since it includes the '%' and the '-' characters.
If you're going to do this in C without an interface library, you must use mysql_real_escape_string to do proper SQL escaping.
There shouldn't be anything intrinsically wrong with using '%inside of a string, though, as the only context in which it has meaning is either directly inprintftype functions or as an argument toLIKE` inside of MySQL.
This proves to be really annoying, but it's absolutely necessary. It's going to make your code a lot more complicated which is why using low-level MySQL in C is usually a bad idea. The C++ wrapper will give you a lot more support.
You really shouldn't escape the string yourself. The safest option is to let the MySQL API handle it for you.
For a string of maximum length n, start by allocating a string of length 2*n+1:
int sidLength = strlen(sid);
// worst-case, we need to escape every character, plus a byte for the ASCIIZ
int maxSafeSidLength = sidLength * 2 + 1;
char *safeSid = malloc(maxSafeSidLength);
// copy "sid" to "safeSid", escaping as appropriate
mysql_real_escape_string(mysql, safeSid, sid, sidLength);
// build the query
// ...
free(safeSid);
There's a longer example at the mysql_real_escape_string page on dev.mysql.com, in which they build the entire query string, but the above approach should work for supplying safeSid to sprintf.
What I've been trying to do is to select a row from a table while treating the varchar cells as int ones,
Here's a little explanation:
I have a table of phone numbers, some have "-" in them, some don't.
I wanted to select a number from the database, without including those "-" in the query.
So I used this preg_replace function:
$number = preg_replace("/[^0-9]/","",$number); //that leaves only the numbers in the variable
and then I run the following query:
"SELECT * FROM `contacts` WHERE `phone` = '{$number}'"
Now, of course it won't match sometimes since the number Im searching may have "-" in the database, so I tried to look for a solution,
on solution is just converting the cells into int's, but I'm not interested in doing that,
So after looking around, I found a MySQL function named CAST, used like : CAST(phone AS UNSIGNED)
I tried to mess with it, but it didn't seem to work.
Edit:
I kept looking around for a solution, and eventually used MySQL's REPLACE function for that.
"SELECT * FROM `contacts` WHERE REPLACE(phone,'-','') = '{$number}'"
Thank you all for your help.
MySQL doesn’t support extraction of regex matches.
You could try writing a stored function to handle it, but your best bet is to convert the data to ints so that all the numbers are uniform. I know you said you don't want to do that, but if you can, then it’s the best thing to do. Otherwise, you could do something like:
"SELECT * FROM `contacts` WHERE `phone` = '{$number}' OR `phone` = '{$number_with_dashes}'"
That is, search for the plain number OR the number with dashes.
1.
The easiest way to do it might be by using the REPLACE operator.
SELECT * FROM `contacts` WHERE REPLACE(REPLACE(`phone`, '-', ''), ' ', '') = '5550100';
What it does is simpy replacing all whitespaces and dashes with nothing, namely removing all spaces and dashes.
2.
Another alternative to solve the problem would be to use LIKE. If the phone numbers with a dash always are formatted the same way like 555-0100 and 555-0199 you can simple insert a %-sign instead of the dash. If your number may be formatted in different ways you can insert a %-between every character. It's not a beautiful solution but it does the trick.
SELECT * FROM `contacts` WHERE `phone` LIKE '555%0100';
or
SELECT * FROM `contacts` WHERE `phone` LIKE '5%5%5%0%1%0%0';
3.
You can use regular expressions. Since MySQL doesn't implement regex replace functions you need to use user defined functions. Have a look at https://launchpad.net/mysql-udf-regexp. It supports REGEXP_LIKE, REGEXP_SUBSTR, REGEXP_INSTR and REGEXP_REPLACE.
Edit: Removed my first answer and added some other alternatives.
I kept looking around for a solution, and eventually used MySQL's REPLACE function for that.
"SELECT * FROM `contacts` WHERE REPLACE(phone,'-','') = '{$number}'"