Add character after two character spaces from right to left - php

I have time stored in my database. Here is an example of a time:
800 or 1000
the first one is 8:00 and the second one is 10:00. I want to add a semicolon : after the second character starting to count from the right to left. how can i do this in php?
here is what i tried:
$realTime = substr_replace($oldtime,":", 2, -strlen($oldtime));
but it started from the left but i need it to start counting from the right. thanks.

Per the docs:
If start is negative, the replacing will begin at the start'th character from the end of string.
So use a negative number:
$realTime = substr_replace($oldtime,":", -2, -strlen($oldtime));

Do it with a regex
$newtime = preg_replace('#^(.*)([0-9]{2})$#','$1:$2',$oldtime);

Another approach is to have different formulas based on the length and use a case statement.
Update foo
set oldtime= case when length(oldtime) = 4 then
concat(substr(oldtime,1,2),':',substr(oldtime,3,2))
when length(oldtime) = 3 then
concat(substr(oldtime,1,1),':',substr(oldtime,2,2))
end
Working Fiddle

Related

How to prevent mysql from adding 2 values with each other in php?

So i want to add some info to the existing info in mysql, so i use this kind of code:
SET date = $alp + number
WHERE id=15 ');
$ES->execute();
$ES->close();
here i got 2 little problems:
When i type an integer, it adds them together. Date is preset as an integer, and i type $alp as 3 for example.
Instead of showing 3 4, it shows like 7. It adds 2 numbers. How do i prevent that? I just want them to stay side by side. Anohter problem when i try to put string, that is kind of fair because letter plus number doesnt work. But how do i make the command so the sql gets it as putting it together and not adding them (doing math i mean). would appriciate answers!
Use CONCAT to "string" the number together in MySQL.. Like so:
SET date = CONCAT($alp, ' number')
Your output will be 3 4
And to concatenate a string in php you would do something like:
$alp = '3';
$alp .= ' 4';
echo $alp;
// output: 3 4

Inconsistent createFromFormat return (PHP)

This works (note the single digit ".3")
$date = DateTime::createFromFormat("*-*-*.*.*-Y-m-d-H?i.*", "backup-bla-3.3.3-2019-08-23-21h16.7z");
This fails (note the double digit ".33" :
$date = DateTime::createFromFormat("*-*-*.*.*-Y-m-d-H?i.*", "backup-bla-3.3.33-2019-08-23-21h16.7z");
This makes no sense to me. Why doesn't the * succeed in this case ?
The following also works on this specific example but I cannot make use of it as the version numbers may have double digits.
$date = DateTime::createFromFormat("*-*-*.*.??-Y-m-d-H?i.*", "backup-bla-3.3.33-2019-08-23-21h16.7z");
Why it fails when using * is clear from the manual:
Random bytes until the next separator or digit
You have two digits in a row 3 and 3 so when it reaches the second 3 your provided format is incorrect and causes an error.
The inverse is true with ** and ?? because when you have a single digit number there is no second character for the second * and ? to match.
I don't see any way around this using the available format characters. Your solution seems to be modifying that value to remove anything before the year and then using Datetime:createFromFormat().
$parts = preg_split('/(?=\d{4})/', 'backup-bla-3.3.3-2019-08-23-21h16.7z', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$date = DateTime::createFromFormat("Y-m-d-H?i.*", $parts[1]);
echo $date->format('c');
Demo

Add zeros at beginning of a number if it is small than 1000

I have an SQL Query
SELECT COUNT(*) AS tot_std
FROM `login`
WHERE `login_account_type` =
'STUDENT'
The output of this query is 9.
What I want is to add:
Three zeros if the number is small than 10, like 0009.
Two zeros if the number is small than 99, like 0099,
One zero if the number is smaller than 999, like 0999.
If the number is equal to or greater than 1000, don't add any zero.
Note that I am using PHP Codeigniter and MySQL for the project.
Please Help.
Try the below code
In your query, you can do like
SELECT LPAD(COUNT(*),4,'0') AS tot_std FROM login WHERE login_account_type = 'STUDENT'
In PHP
$your_value = 9;
$your_value = str_pad($your_value,4,'0', STR_PAD_LEFT);
echo $your_value;
str_pad() function will add leading zeros. The second parameter shows the total number. As you need it for thousands, I add 4. The 3rd parameter represent which character added at the beginning. The fourth parameter is the side where you need to add the zero
Use this :
"SELECT lpad(tot_std,4,0) as tot_std FROM login WHERE login_account_type='STUDENT'" ;

Search phone number in database table

I have a phone record tables as
phones(id, number);
It may have values as:-
1, 9801234567
2, 980 1234568
3, 9779801234569
4, 9801234570
5, 977 980 1234 571
If someone search for 980 1234567 (with spaces), I can remove the spaces before running the queries to get the result.
But my problem is when someone search for 9779801234571 with a condition that there is no regular format of number, it must return the last record i.e. 977 980 1234 571. Any idea how to do it efficiently?
Here is a way to do this:
where replace(phonenumber, ' ', '') = replace($phonenumber, ' ', '')
Doing this efficiently is another matter. For that, you would have to format your phone numbers in the database in a canonical format -- say by removing all the spaces in an update statement. Then put the number you are searching for in the same format. The query can then use an index on the column.
It is probably best to clean the phone numbers from whitespace before you write them into the database. You can easily to this using this function:
$string = preg_replace('/\s+/', '', $string);
Maybe you also have to strip out other characters like - or /.
Then you can use a simple WHERE condition without bells and whistles. This will also significantly improve the performance of your SELECT statement since you don't have to do conversions of your data in order to find the right row.
This is assuming that you fill the database yourself of course. If that's not the case, ignore this advise.

Change specific character of a text in MySQL

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

Categories