Avatar of Boban Gogic
Boban Gogic

asked on 

PHP, MySQL Insert data from first table into second, third and fourth

I have one table called users (id, username, password), second table called profiles (id, user_id, username, name, lastname, age, gender, country, company_name), third table called companies (id, user_id, name, resources_id) and fourth table called resources (id, user_id, company_id, money). When users register their account, they need to create their profile. Now when they fill profile data, profiles and companies tables are filled just fine.

My problem is in resources table:
Error: Incorrect integer value: '' for column 'company_id' at row 1
When I refresh that page with error, resources table is filled fine, but now I got double rows for profiles and companies tables.

My code:
<?php
    session_start();

    $dbserver                    = "localhost";
    $dbusername                  = "root";
    $dbpassword                  = "1234512345";
    $db                          = "game";

    $conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);

    if ($conn->connect_error)
    {
        die("Connection failed: ".$conn->connect_error);
    }

    if(isset($_SESSION['loggedin']))

    $username = $_SESSION['loggedin'];

    $query = "SELECT id FROM users WHERE username = '$username'";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_assoc($result);

    $userId = $row['id'];
    $_POST['id'] = $userId;

    $name = $_POST['name'];
    $lastname = $_POST['lastname'];
    $age = $_POST['age'];
    $gender = $_POST['gender'];
    $country = $_POST['country'];
    $company_name = $_POST['company_name'];
    $_POST['loggedin'] = $username;

    $query = "SELECT id FROM companies WHERE name = '$company_name'";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_assoc($result);

    $companyId = $row['id'];
    $_POST['id'] = $companyId;

    //INSERT DATA INTO PROFILES
    $sql = "INSERT INTO profiles (user_id, username, name, lastname, age, gender, country, company_name)
    VALUES ('$userId', '$username', '$name', '$lastname', '$age', '$gender', '$country', '$company_name')";

    //INSERT DATA INTO COMPANIES
    $sql2 = "INSERT INTO companies (user_id, name)
    VALUES ('$userId', '$company_name')";

    //INSERT DATA INTO RESOURCES
    $sql3 = "INSERT INTO resources (user_id, company_id)
    VALUES ('$userId', '$companyId')";

    if($conn->query($sql) && $conn->query($sql2) && $conn->query($sql3) === TRUE)
    {
        header("Location: ../../index.php?page=profile");
        die();
    }
    else
    {
        echo "Error: ".$conn->error;
    }
?>

Open in new window

What should I do differently? I'm still beginner into this, sorry for long post.
HTMLDatabasesPHPMySQL Server

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon