Johannes Botéus Johannes Botéus - 2 months ago 8
PHP Question

How do I create a variable which goes up with '1' everytime it's used and resets at the end of the month?

I'm still quite new to php and javascript etc, and I'm doing my register.php file for an app I'm working on and now I want every user who registers to get an unique ID and this is what I got:

<?php echo date("Ymd") ?>


This gives me (right now) 20161005 and I want this to be part of my ID's for my users and then I want to add a number to that for example

$userID= date('Ymd') + some number


This number should begin from 1 again in the beginning of the next month so my database doesnt get to many number in the end :)

This combination of those 2 numbers will be my User ID's which will help me to deter whoms data to load in the app and so on.. ^^

Is that possible to realise with php?

Answer

Not to say you are doing it wrong, but you should consider using the AUTO_INCREMENT property built into the DB. This will give you a integer number that automatically increases with each insert.

You can set it as an Attribute of the table,

dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html

And then when doing inserts you just leave that field out, and magically it will be incremented. If you need to use it immediately after doing the insert you can get its value with ( in MySqli )

  mysqli_insert_id( $db );

http://php.net/manual/en/mysqli.insert-id.php

Then for the created time, you should use a proper data type such as a timestamp or datetime. This too can be set to have a default value of NOW() the current time. Then when you do date based queries you can use things like MONTH( create_date ) to find all users that singed up in a given month etc..

Here is a wiki page on what I meant by Surrogate key

https://en.wikipedia.org/wiki/Surrogate_key

Basically it's just a unique identifier not derived from the actual data. Then being these are users a good example of a Natural key would be the email address, being that users email should be unique in most cases.