I want to complete user sign up.
firstly user will write username and password, table called users, I have id as primary key.
secondly user will write address, phone number and zipcode, table called userdata, I have userid as index(key).
I have did a relation between id from table user and userid from table userdata.
So now I want to insert data from php code I did two forms one for user and it has two input for username and password it works well and data inserted.
in the second form I have select option has id from table users and it works well.
then in the same form I have three inputs phone number, address and zipcode.
so the question is how I can insert the data to userdata by the same to the same id. so userid in table user will be the same id in table userdata.
I need sql code.
I used that :
"INSERT INTO userdata(address, phone, zipcode) VALUE (:address, :phone, :zip) SELECT 'id' FROM 'users';"
First :
$q = "NSERT INTO users(username, password) VALUE ('Adam', '12345678')";
$r = $connect->query($q);
//get the last id u inserted
$last_id = mysqli_insert_id($connect);
Second :
$q = "NSERT INTO userdata(address, phone, zipcode,user_id) VALUE ('California', '12345678', '1111','$last_id')";
$r = $connect->query($q);
and if you want to make the (id) not the (userid) the same just :
$q = "NSERT INTO userdata(id, address, phone, zipcode) VALUE ('$last_id','California', '12345678', '1111')";
$r = $connect->query($q);
Related
the code works fine when it is only one user but once i create a second user, the data doesn't get inserted into the database
$sql = "INSERT INTO images ( users_id, picture, Carehome, dateworked, hours)
VALUES ((SELECT id FROM users ), '$target_file', '$Carehome', '$dateworked', '$hours')";
You call all users ID
SELECT id FROM users
You can solve it by get it id by id
<?php
$sql_ids = "SELECT id FROM users";
//get users row by row
//your_db_conn is example you must replace it by your variable
while($row = mysqli_fetch_assoc(mysqli_query(your_db_conn,$sql_ids))){
//save user id in $id
$id = $row['id'];
$sql = "INSERT INTO images ( users_id, picture, Carehome, dateworked, hours)
VALUES ('$id', '$target_file', '$Carehome', '$dateworked','$hours')";
mysqli_query(your_db_conn,$sql);
}
?>
Make sure user id is not a primary key in images table
I'm a bit lost and cant find anything to guide me in the right direction so maybe some of you got a suggestion. Im trying to do add items in a list.
First of all I have a user table which contains the users id. This id is put as a session so when the user creates adds a list their id is inserted in the list table, so I know which user the list belolngs to. The list table aslo contains a listname and an unique id which is gained from auto increment.
List:
id(from user) ai Listname
1 1 List one
1 2 List two
3 3 List one
My next table is to add items in the list. It contains the ai from list, and its own auto increment and the name on the item.
ai(from list) itemAi itemName
? ? ?
What I dont get is to insert it. Lets say I created a list a its in my table and I insert an item name and itemAi gets automaticly set, how do I set which list I'm currently in? Do i set it as a session or what's the normal approach?
Update:
$name = 'Test';
$sql = $con->prepare('INSERT INTO list (name) VALUES (?)');
$sql->bind_param("s",$name);
$sql->execute();
$sql->close();
$user = $_SESSION['user_id'];
$qq = $con->prepare('INSERT INTO user_list (user_id, list_id) VALUES (?,?)');
$qq->bind_param("ss", $user,????);
$qq->execute();
$qq->close();
$con->close();
I'd try to normalize your tables into logical concepts: user, list, item etc. Then, use join tables to create the many-to-many relationships between them.
Tables:
user: id (auto-increment), first name, last name, ...
list: id (auto-increment), name
item: id (auto-increment), name
user_list: user_id (FK to user.id), list_id (FK to list.id)
user_list_item: user_id (FK to user.id), list_id (FK to list.id), item_id (FK to item.id)
*FK = foreign key. There are ways to shorten this up a bit, but I'd go for the explicit structure here to keep things clean and separated.
Then, in PHP you keep track of your user and the list they're currently working on in the session.
<?php
// After logging in
$_SESSION['user_id'] = ...;
// Choose which list the user is working on
$_SESSION['list_id'] = ...;
If they haven't chosen a list to work with, force them to. This is part of the validation.
Now every time the user wants to make changes, use those session values.
Your business logic would be:
<?php
// Associate a list with a user
INSERT INTO `user_list` (user_id, list_id) VALUES (?, ?)
?: $_SESSION['user_id']
?: $_SESSION['list_id']
// Disassociate a list from a user
DELETE FROM `user_list` WHERE user_id = ? AND list_id = ?
?: $_SESSION['user_id']
?: $_SESSION['list_id']
// Insert a new item into a user's list
$itemId = INSERT INTO `item` (name) VALUES (?)
?: 'Bread'
INSERT INTO `user_list_item` (user_id, list_id, item_id) VALUES (?, ?, ?)
?: $_SESSION['user_id']
?: $_SESSION['list_id']
?: $itemId
// Clear our the items from a specific list
DELETE FROM `user_list_item` WHERE user_id = ? AND list_id = ?
?: $_SESSION['user_id']
?: $_SESSION['list_id']
// Empty all items for a given user, but keep the lists intact.
DELETE FROM `user_list_item` WHERE user_id = ?
?: $_SESSION['user_id']
// Remove a specific item from a user's list
DELETE FROM `user_list_item` WHERE user_id = ? AND list_id = ? AND item_id = ?
?: $_SESSION['user_id']
?: $_SESSION['list_id']
?: $itemId
Lets say the user inserts a new list and I insert its name and an id
on the list gets A.i. Then at the same time I have to insert the
session user_id and the list_id in user_list, the user id is set from
session, but how do I get the list_id on the new created list?
Good question. Most RDBMs give you a function to get the last inserted ID. PDO specifically exposes it via lastInsertId.
In this case, you'd issue 2 insert statements. The first one will create the new list and the second will associate the list with the user by grabbing the ID of the newly created list and the current user ID from the session.
<?php
// Create a new list and assign it to a user
// The form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Connection to your DB.
// See https://phpdelusions.net/pdo#dsn for a decent tutorial on PDO.
$pdo = new PDO(...);
// Get the name from the submitted form
$listName = $_POST['name'];
// Create the list and get the ID of the newly created list.
$stmt = $pdo->prepare('INSERT INTO `list` (name) VALUES (?)');
$stmt->execute([$listName]);
$listId = $pdo->lastInsertId();
// Now, associate the new list with the user.
$stmt = $pdo->prepare('INSERT INTO `user_list` (user_id, list_id) VALUES (?, ?)');
$stmt->execute([$_SESSION['user_id'], $listId]);
}
I have four fields in table id, name, city & state. I am inserting name , city & state. and id is auto increament
$mysql_register_resultset= mysqli_query($con, "INSERT into vendor (username, city, state) VALUES( '$name','$city','$state')");
It is successfully sumitted. I want that id value on next line of insertion. and i will process with that id.
How to get current id after insertion.
use this
$last_inserted_id = mysqli_insert_id($con) ;
I recently asked a question about writing to multiple tables: PHP/MySQL insert into multiple data tables on submit
I have now tried out this code and there are no errors produced in the actual code but the results I am getting are strange. When a user clicks register this 'insert.php' page is called and the code can be found below.
<?php
$username = $_POST["username"];
$password = $_POST["password"];
$institution = $_POST["institution"];
$conn = pg_connect("database connection information"); //in reality this has been filled
$result = pg_query($conn, "INSERT INTO institutions (i_id, name) VALUES (null, '$institution') RETURNING i_id");
$insert_row = pg_fetch_row($result);
$insti_id = $insert_row[0];
// INSTITUTION SAVED AND HAS ITS OWN ID BUT NO MEMBER OF STAFF ID
$resultTwo = pg_query($conn, "INSERT INTO staff VALUES (NULL, '$username', '$password', '$insti_id'");
$insert_rowTwo = pg_fetch_row($resultTwo);
$user_id = $insert_rowTwo[0];
// USER SAVED WITH OWN ID AND COMPANY ID
// ASSIGN AN INSTITUTION TO A STAFF MEMBER IF THE STAFF'S $company_id MATCHES THAT OF THE
// INSTITUION IN QUESTION
$update = pg_query($conn, "UPDATE institutions SET u_id = '$user_id' WHERE i_id = '$insti_id'");
pg_close($conn);
?>
What the result of this is just the browser waiting for a server response but there it just constantly waits. Almost like an infinite loop I'm assuming. There are no current errors produced so I think it may be down to a logic error. Any ideas?
The errors:
RETURNING clause is missing in the second INSERT statement.
Provide an explicit list of columns for your second INSERT statement, too.
Don't supply NULL in the INSERT statements if you want the column default (serial columns?) to kick in. Use the keyword DEFAULT or just don't mention the column at all.
The better solution:
Use data-moidifying CTE, available since PostgreSQL 9.1 to do it all in one statement and save a overhead and round trips to the server. (MySQL knows nothing of the sort, not even plain CTEs).
Also, skip the UPDATE by re-modelling the logic. Retrieve one id with nextval(), and make do with just two INSERT statements.
Assuming this data model (you should have supplied that in your question):
CREATE TABLE institutions(i_id serial, name text, u_id int);
CREATE TABLE staff(user_id serial, username text, password text, i_id int);
This one query does it all:
WITH x AS (
INSERT INTO staff(username, password, i_id) -- provide column list
VALUES ('$username', '$password', nextval('institutions_i_id_seq'))
RETURNING user_id, i_id
)
INSERT INTO institutions (i_id, u_id, name)
SELECT x.i_id, x.user_id, '$institution'
FROM x
RETURNING u_id, i_id; -- if you need the values back, else you are done
Data model
You might think about changing your data model to a classical n:m relationship.
Would include these tables and primary keys:
staff (u_id serial PRIMARY KEY, ...)
institution (i_id serial PRIMARY KEY, ...)
institution_staff (i_id, u_id, ..., PRIMARY KEY(i_id, u_id)) -- implements n:m
You can always define institution_staff.i_id UNIQUE, if a user can only belong to one institution.
I am trying to insert data into a table (table1) based on another (table2), the only problem is that table1 contains fields set to not allow null values. Do I need to create these fields in table2 where I am pulling the data from and populate them with a value?
Example not null field: password
If I do not include this in my query then I get an error and the record is not inserted however if I create the field in table2 then insert into my query it works fine. This seems a bit out of the ordinary. Example query below:
Example 1 (no password field in table 2):
$insert_new_records_query = "INSERT INTO table1 (first_name, last_name, email_address) ".
"SELECT firstname, lastname, email FROM table2";
This generates an error saying that I must include the password field.
Example 2 (password field in table 2):
$insert_new_records_query = "INSERT INTO table1 (first_name, last_name, password,
email_address) ".
"SELECT firstname, lastname, password = 'password1', email FROM table2";
This allows the record to be created. The problem is that I have many more fields that are not null in table 1 and I don't think I need to create them in table 2 as blank fields and insert them into my query with values just to create a record. Is there a better way to do this?
You don't have to create fields, you can simply 'select' default values. Try this instead:
INSERT INTO table1 (first_name, last_name, password, email_address)
SELECT firstname, lastname, 'password1', email FROM table2