Dear forum users! I need your help!

Tell me how right? The task is simple, you need to record the user's visit to the database .

  • Connect to the database.
  • We update the record about the visitor in the table.
  • And what if the visitor is for the first time and his record is not there, then we insert the record.
  • For deployment (for the first run): What if there is no table, then we create a table.

Question 1: It is disturbing that every time you update (update) a bunch of idle operations (create, insert), it can somehow be solved differently, tell me.

Question 2: How do you solve the tasks that are required once during the first start?

Question 3: Connect to the database. Can move to another file? But then when you move the file there will be problems, and if you leave - it constantly opens and closes the connection to the database in different files.

$db = new PDO('sqlite:file.sqlite'); $db -> exec("CREATE TABLE IF NOT EXISTS 'tableName' ( id PRIMARY KEY AUTOINCREMENT, user TEXT UNIQUE NOT NULL, visitCounter INTEGER DEFAULT '0' )"); $db -> exec("INSERT OR IGNORE INTO 'tableName' (user) VALUES ('user1')"); $db -> exec("UPDATE 'tableName' SET visitCounter = visitCounter + 1 WHERE user = 'user1'"); unset($db); 
  • one
    Table in the database can be created in advance. It is better to do the connection with the database in one place, and then just give it away. - Ivan Bolnikh

1 answer 1

1.2. You will have to perform them because you need to check whether this record really exists. I certainly don’t know the architecture of your system. But I'd rather add it to the right tables with the creation of the user and then it would not be necessary to prescribe INSERT every time

3. Connection to the database should be in a separate file and in the script where you will need to work with the database, you connect it using require()

  • You are right, probably my problem arises because some users already have, and some will be added later - tonchikp