0

My app automatically checks when the customer logs in and only gives back one access_token and one shop values.

Below is the table with headings and a row of example data

access_token shop
111111111 shop1

Sometimes a new customer installs the app and a new shop and access_token is created and I need to INSERT all new data in each column.

Other times the customer has re-installed the app so the shop exists but the access_token has changed and I need to update it.

How do I INSERT if none exist, but UPDATE if a value (shop) exists and another (access_token) doesn't when I am only given a single value of each?

I have attempted with ON DUPLICATE KEY UPDATE below where the shop is the same but the access_token has changed, but because I only get given one access_token to check when the customer logs in to the app it would just insert and not update.

INSERT INTO customers (access_token, shop)
VALUES(111, "shop1")
ON DUPLICATE KEY UPDATE access_token=111

I have attempted an example below where the shop is the same but the access_token has changed, however, I keep getting syntax errors. Please help, thank you.

SELECT EXISTS(SELECT shop FROM customers WHERE shop = 'shop1') AS sp,
NOT EXISTS (SELECT access_token FROM customers WHERE access_token = '{999999999}') AS tk

    IF sp AND tk = 1
        UPDATE customers
        SET access_token='999999999'
        WHERE shop = 'shop1';

    ELSEIF NOT EXISTS (SELECT shop FROM customers WHERE shop = 'shop1') THEN
        INSERT INTO customers (access_token, shop)
        SELECT * FROM (SELECT '999999999', 'shop1') AS tmp;

    END IF;
DidSquids
  • 149
  • 1
  • 8
  • the mysql statement you have posted above can be used in stored procedure in mysql, not in general form, refer - https://www.tutorialspoint.com/How-can-MySQL-IF-ELSEIF-ELSE-statement-be-used-in-a-stored-procedure – Karthick Jan 17 '21 at 13:36
  • 1
    Did you set `shop` to be unique, the on dup only works if something is being duplicated that should not be duplicated – RiggsFolly Jan 17 '21 at 14:02
  • Oh, good call @RiggsFolly the 'shop' column is not set to unique in the table. I have just made the column unique and now the ON DUPLICATE KET UPDATE functions the way I wanted it to. Thanks so much! I've been trying to work this out for ages. – DidSquids Jan 17 '21 at 14:52

1 Answers1

-2

Are you using purely MySQL? I have made a signup and login page before as part of a web app and used Php to do this. I believe you can use Php for apks so I will write in Php, but you should be able to translate to your language with ease.

<?php
if (isset($_POST['signup-submit'])) {  //this is so that the following can only be done on 
                                         the button press (name of it is signup-submit)
    
    require 'dbh.inc.php';

    $username = $_POST['Username'];
    $email = $_POST['mail'];
    $password = $_POST['pwd'];
    $confirmpassword = $_POST['cpwd']; //this is all off the details of the user passed 
                                         through to be run through this script into the 
                                         database
if (empty($username) || empty($email) || empty($password) || empty($confirmpassword)) {
    header("Location: ../index.php?error=emptyfields&uid=". $username. "&mail=". $email);
    exit();
            }  //checking for empty fields

else if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9 ]*$/", $username)) {
    header("Location: ../index.php?error=invalidemail&uid");
    exit();
            }
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header("Location: ../index.php?error=invalidemailuid");
    exit();
            }
else if (!preg_match("/^[a-zA-Z0-9 ]*$/", $username)) {
    header("Location: ../index.php?error=invaliduid&email=". $email);
    exit();
            }
            else if ($password !== $confirmpassword) {
    header("Location: ../index.php?error=checkpasswords&mail=".$email. "&uid=".$username);
    exit();
            }  //checking all characters used are only that which you allow


else {
        $sql = "SELECT uidusers FROM users WHERE uidusers=?";
        $sqly = "SELECT emailusers FROM users WHERE emailusers=?";
        $stmt = mysqli_stmt_init($conn);
        if (!mysqli_stmt_prepare($stmt, $sql)) {
            header("Location: ../index.php?error=sqlerror");
            exit();
                    }  //using prepared statements to insert user info
            else {
                mysqli_stmt_bind_param($stmt, "s", $username);
                mysqli_stmt_execute($stmt);
                mysqli_stmt_store_result($stmt);
                $resultCheck = mysqli_stmt_num_rows($stmt);
                if ($resultCheck > 0) {
                header("Location: ../index.php?error=usertaken&mail=". $email);
                exit();
                        }    //checking for existing details
        
                    
                if (!mysqli_stmt_prepare($stmt, $sqlx)) {
                    header("Location: ../index.php?error=sqlerror");
                    exit();
                            }
    
                    
                            if (!mysqli_stmt_prepare($stmt, $sqly)) {
                            header("Location: ../index.php?error=sqlerror");
                            exit();
                                    }
                            else { 
                                    mysqli_stmt_bind_param($stmt, "s", $email);
                                    mysqli_stmt_execute($stmt);
                                    mysqli_stmt_store_result($stmt);
                                    $resultCheck3 = mysqli_stmt_num_rows($stmt);
                                    if ($resultCheck3 > 0) {
                                    header("Location: ../index.php?error=emailtaken");
                                    exit();
                                            }  //storing details
                                            
                        
            
                                    else { 
                                        $sql = "INSERT INTO users (uidusers, emailusers, 
                                                pwdusers, invcode) VALUES (?, ?, ?, ?) ";
                                        $stmt = mysqli_stmt_init($conn);
                                        if (!mysqli_stmt_prepare($stmt, $sql)) {
                                        header("Location: ../index.php?error=sqlerror");
                                        exit();
                                                }

                                                        else {
                                                                $hashedpwd = password_hash($password, PASSWORD_DEFAULT);  //hashing passwords
            
                                                                mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashedpwd);
                                                                mysqli_stmt_execute($stmt);
                                                                header("Location: ../index.php?signup=success");  //all details stored successfully


As for your access token, I would suggest adding a function to run a uniqid() function along with another function to check for existing tokens so that duplicates aren't made ( I did this for another similar reason to yours) and then using similar code as above to write that in.

I'm not sure what your shop ID is for but I have options for 2 eventualities:

If it's just a sort of ID, auto increment it in the database

If it's to show which shop the person entered, use foreign keys to link the column to a parent table with all the shops listed and set the relationship to cascade. Then make a button to switch shops that will

A) send an update to the database, overwriting the child column and row of the user

B) redirect the user to the new shop

(I have no idea why the second half of the code is green, but if you remove my comments you should be good, though I'd advise you to write your own code so that you can see how it works and adapt it to your own project)

Atristamez
  • 31
  • 5
  • Thanks for the response, it was very helpful. I am using python but was trying to do it in purely MySQL. Although it would be much easier for me to integrate python to. – DidSquids Jan 17 '21 at 13:45