How to remove time stamp and date from a string - php

I have added time stamp and date when the details should create. and the time stamp and date will add in database. When i'll retrieve it from db it wanna to show only that string name without time stamp and date ? how to make it?
Adding Method....
$imagename = $_POST['imagename'];
$imageNameExt = $_POST['imageNameExt'];
$newImgName = trim($imagename).'_'.date('Y_m_d_H_i_s').'.'.trim(strtolower($imageNameExt));
Here consider the $imagename = "abc"; and $imageNameExt = "jpg"; when it'll insert into db the name as $newImgName = "abc_2011_07_12_18_47_02.jpg"....
Now i need to retrieve from db..How should i print only the name "abc" with out the time stamp and date??
Thanks in advance.
Update : (I couldn't post this as a answer bcoz am under 100 reputation.)
found the answer for my question:
While am retrieving it'll come in the name of image_path,
$image_path = $rows[0];
$tmp = "_".date('Y');
$ImgOrgName = explode($tmp,$image_path);
$ImgOrgName_core = $ImgOrgName[0];
The Image name "abc" will come in the string "$ImgOrgName_core".
Try it...i'm easily getting the answer when i use like this.

You should store the original image name and the timestamp information as separate columns in the database. This way you will always have access to each piece of data, and you can concatenate them as you currently do before inserting any time you wish.
You can also hammer your existing code into submission by simply getting the string and counting underscores from the end until you find the 6th (there are 5 in the timestamp so the 6th from the end separates the timestamp from the name), or you can simply remove the last 20 characters from the name with substr (the timestamp is 19 chars if all numbers are padded with zeroes, plus 1 char for the separator underscore), but this kind of solution is messy and prone to breakage. I would never recommend it, so I don't give code for it (and anyway, cutting off the last 20 characters is trivial).

You cat replace date with regexp:
$imgNameNoDate = preg_replace('#_\d{4}_\d{2}_\d{2}_\d{2}_\d{2}_\d{2}#', '', $imgName);
But better way is to change your database to store original name and datetime information.

While I agree with the commenters that it would be much, much better to store the timestamp in its own column, here's how to do specifically what you want.
$underscorePos = strpos($imageNameFromDB, '_');
if ($underscorePos !== false)
{
$imageNameOnly = substr($imageNameFromDB, 0, $underscorePos);
}

found the answer for my question:
While am retrieving it'll come in the name of image_path,
$image_path = $rows[0];
$tmp = "_".date('Y');
$ImgOrgName = explode($tmp,$image_path);
$ImgOrgName_core = $ImgOrgName[0];
The Image name "abc" will come in the string "$ImgOrgName_core".
Check it...i'm easily getting the answer when i use like this.

Related

Retrieving Mktime values from Mysql using PHP

On my website I am attempting to make a countdown timer. The same code for the timer works if I tell it the value of the column and it works on a test php page. The problem is that the mktime value is not being read right from the mysql database. However if I put the column to output inside of an echo it outputs fine. The column that contains the data is called expire. The other values I am loading from mysql are inside of he echo however all connection statements are made before I call any. I am using the mysqli_fetch_array to call the values.
$target = mktime($row['expire']);
$today = time();
$difference = $target-$today;
$hours = $difference/3600;
$minutes = ($hours-floor($hours))*60;
echo('ENDS IN: '.floor($hours).' Hrs '.floor($minutes).' Mins');
Yes the document is HTML that it gets included into
The way I formatted the expire column in mysql was standard as Hr,Min,Sec,MM,DD,YYYY. The actual content of the column is "21,0,0,7,12,2017"
Thanks in advance, David.
The problem is, that you get a string from your database in $row['expire']. But mktime() is an integer only function. So, first you need a workaround to explode and convert your string to integers, before it will work with mktime().
Please delete the following line from your code:
$target = mktime($row['expire']);
Try this instead:
$timeparts = array_map('intval', explode(',', $row['expire']));
$target = mktime($timeparts[0],$timeparts[1],$timeparts[2],$timeparts[3],$timeparts[4],$timeparts[5]);
Hope it was helpful. But please do not save timevalues as a string in your database. Read about other possibilities in the manual.

sequence id increment with date - laravel

I'm trying to create an increment number licence with the current date of the year + an increment number but i really don't know how to do this i know MYSQl does not support sequences but i would like to know if there is a way to solve the problem
here my controller
public function create(){
$licence = new Licence ;
$licence ->num_licence = Carbon::now()->year -- i would like here to put the current year like 2017 with a random unique number to get the format like 20170001 for exemple !
...
how to acheice this? thanks in advance :)
you can use uniqid function with current year as prefix.
public function create(){
$licence = new Licence ;
$num_liscence_exist=true;
while($num_liscence_exist){
$num_liscence=uniqid(Carbon::now()->year);
if (!Liscence_Table::where('num_liscence', '=',"'".$num_liscence."'")->exists()) {
$liscence->num_liscence=$num_liscence;
$num_liscence_exist=false;
}
}
}
Generate the random id using uniqid() and concatenate with date:
public function create(){
$liscence=new Liscence();
$year = Carbon::now()->year;
$liscence->num_liscence= $year. uniqid();
$liscence->save();
}
using uniqid() get unique number or also you can use time stamp with it:
$liscence=new Liscence();
$year = Carbon::now()->year;
$liscence->num_liscence= $year. strtoupper(uniqid()) . Carbon::now()->timestamp;
$liscence->save();
Will look like : 2017ABC011486543961
A sequence needs to be stored somewhere so I doubt there's a sensible pure-PHP solution. But since you're already using MySQL there's no reason to not use it. I'd create a database table for that, something like:
CREATE TABLE licence_sequence (
sequence_year YEAR NOT NULL,
next_value INT UNSIGNED NOT NULL DEFAULT 1,
PRIMARY KEY (sequence_year, next_value)
)
ENGINE=InnoDB;
(Ugly sequence_year name was chosen to avoid having to quote it every time.)
You then have to manage this from code, including:
Ensuring you have rows for every year as you need them (this can be as simple as populating data for all years for next century).
Ensuring you don't assign the same value to different items.
A rough overview of stuff to consider:
You can (and should) make your licence number a unique index to avoid dupes.
You can use transactions to avoid unnecessary gaps. Transaction should wrap all the operations involved:
Get next sequence number
Save it into new licence
Increment next number
You need to ensure atomic operations in a multi-tasking environment. This is the hardest part. I've been lately being playing with MySQL named locks and they seem to work correctly.

Random string gets repeated?

I have a service on the internet where people post pictures and a short string is generated. Only one can be used ever. However, I am getting into duplicates in the database and I am seeing major problems.
Here's what I am using:
$id=rand(10000,99999);
$short_string = base_convert($id,20,36);
What would be the best way to fix it? Check from the database and keep looping till it doesn't match one? What if every possible solution and it goes in an infinite loop?
Increment the last value by a random amount instead of using a random value. Like so:
$results = mysql_query("SELECT * FROM thetable ORDER BY theId DESC LIMIT 1");
$keyToUse = 1;
if($row = mysql_fetch_array($results)) {
$keyToUse = (int)$row['theId'] + rand(1, 100);
}
Then convert the integer key to and from any format, say using base_convert.
Put your PK through an algorithm that generates a unique number from it and put that through your function.
The best bet would be to make sure the image doesn't exist by using the random number generator against the list of images before writing a new image with that number in it.
Try to increase the amount and type of characters by using an algorithm that uses numbers, letters so it increases the combinations that you can have.
Did you try using mt_rand() http://www.php.net/manual/en/function.mt-rand.php. Also you should be increasing the range.
Use md5 http://php.net/manual/en/function.md5.php
The strings produced have no conflict (with large probability).

While loop for mysql database with php?

I am developing a mysql database.
I "need" a unique id for each user but it must not auto increment! It is vital it is not auto increment.
So I was thinking of inserting a random number something like mt_rand(5000, 1000000) into my mysql table when a user signs up for my web site to be. This is where I am stuck?!
The id is a unique key on my mysql table specific to each user, as I can not 100% guarantee that inserting mt_rand(5000, 1000000) for the user id will not incoherently clash with another user's id.
Is there a way in which I can use mt_rand(5000, 1000000) and scan the mysql database, and if it returns true that it is unique, then insert it as the user's new ID, upon returning false (somebody already has that id) generate a new id until it becomes unique and then insert it into the mysql database.
I know this is possible I have seen it many times, I have tried with while loops and all sorts, so this place is my last resort.
Thanks
You're better off using this: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid
Or using this: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
But if you actually want to do what you are saying, you can just do something like:
$x;
do {
$x = random_number();
"SELECT count(*) FROM table WHERE id = $x"
} while (count != 0);
// $x is now a value that's not in the db
You could use a guid. That's what I've seen done when you can't use an auto number.
http://php.net/manual/en/function.com-create-guid.php
Doesn't this function do what you want (without verification): http://www.php.net/manual/en/function.uniqid.php?
I think you need to approach the problem from a different direction, specifically why a sequence of incrementing numbers is not desired.
If it needs to be an 'opaque' identifier, you can do something like start with a simple incrementing number and then add something around it to make it look like it's not, such as three random numbers on the end. You could go further than that and put some generated letters in front (either random or based on some other algorithm, such as the day of the month they first registered, or which server they hit), then do a simple checksuming algorithm to make another letter for the end. Now someone can't easily guess an ID and you have a way of rejecting one sort of ID before it hits the database. You will need to store the additional data around the ID somewhere, too.
If it needs to be a number that is random and unique, then you need to check the database with the generated ID before you tell the new user. This is where you will run into problems of scale as too small a number space and you will get too many collisions before the check lucks upon an unallocated one. If that is likely, then you will need to divide your ID generation into two parts: the first part is going to be used to find all IDs with that prefix, then you can generate a new one that doesn't exist in the set you got from the DB.
Random string generation... letters, numbers, there are 218 340 105 584 896 combinations for 8 chars.
function randr($j = 8){
$string = "";
for($i=0;$i < $j;$i++){
srand((double)microtime()*1234567);
$x = mt_rand(0,2);
switch($x){
case 0:$string.= chr(mt_rand(97,122));break;
case 1:$string.= chr(mt_rand(65,90));break;
case 2:$string.= chr(mt_rand(48,57));break;
}
}
return $string;
}
Loop...
do{
$id = randr();
$sql = mysql_query("SELECT COUNT(0) FROM table WHERE id = '$id'");
$sql = mysql_fetch_array($sql);
$count = $sql[0];
}while($count != 0);
For starters I always prefer to do all the randomization in php.
function gencode(){
$tempid=mt_rand(5000, 1000000);
$check=mysql_fetch_assoc(mysql_query("SELECT FROM users WHERE id =$tempid",$link));
if($check)gencode();
$reg=mysql_query("INSERT INTO users id VALUES ('$tempid')",$link);
//of course u can check for if $reg then insert successfull

Problems with serialize() and unserialize() - inserting and selecting data PHP MySQL

I am attempting to grab a date supplied via POST, then generate a list of dates over a 12 week period from the supplied start date. These dates would then go into the DB and a 12 week schedule would be output, which the user can interact with (add/edit/delete).
I am successfully taking the start date, generating the 12 week date list and adding this into the DB in serialized form, but when it comes to selecting the dates for display, I get the following error:
Notice: unserialize() [function.unserialize]: Error at offset 0 of xxx bytes in ...
Here is my code:
1st .php file here to take a form input (a date) and then get a list of each date over a 12 week period from the start date, and insert into the DB:
The array:
$start = strtotime($_POST['Start_Date']);
$dates=array();
for($i = 0; $i<=84; $i++)
{
array_push($dates,date('Y-m-d', strtotime("+$i day", $start)));
}
$savetodb = serialize($dates);
The insert:
$sql = "INSERT INTO programme VALUES (NULL, '20', '".$_POST["Start_Date"]."' , ' ".$savetodb." ', '".$_POST["Programme_Notes"]."')";
2nd .php file here - SELECT and unserialize:
$result = mysql_query("SELECT Programme_Dates FROM programme");
while($row = mysql_fetch_array($result))
{
$dates = unserialize($row["Programme_Dates"]);
echo $dates;
}
From what I've read the problem could be related to the DB column where the serialized array is inserted (ie being too small), but it is set to TEXT so that should be fine right? I also thought there may be certain characters within a date causing problems, but when testing with a "regular" array (ie just text), I get the same errors.
Any suggestions / hints much appreciated, thanks.
Why are you using stripslashes? My bet is that is the problem. Remove that from there and see if it works.
As a side note, stripslashes should be avoided as if data is probably inserted into the database they should be escaped properly meaning no extra slashes should be added. If you need to stripslashes from the data itself I would suggest using something like array_filter after you unserialized the array.
EDIT
You should also look into SQL Injection and how to prevent it, as your code is suseptible to be exploited.
UPDATE
Looking further at your code you insert the serialized array with 2 extra spaces: ' ".$savetodb." ', try using just '".$savetodb."', that and see if it fixes your issue.
i have found that the serialize value stored to database is converted to some other way format. Since the serialize data store quotes marks, semicolon, culry bracket, the mysql need to be save on its own, So it automatically putting "backslash()" that comes from gpc_magic_quotes (CMIIW). So if you store a serialize data and you wanted to used it, in the interface you should used html_entity_decode() to make sure you have the actual format read by PHP.
here was my sample:
$ser = $data->serialization; // assume it is the serialization data from database
$arr_ser = unserialize(html_entity_decode($ser));
nb : i've try it and it works and be sure avoid this type to be stored in tables (to risky). this way can solve the json format stored in table too.

Categories