Using LastInsertId Multiple times, PHP PDO - php

I have this registration stuff, and I want to 3 tables to be filled with data as soon as the user clicks add user
the tables were:
users
roles
status
user_role
user_status
The system must insert the data as follows
users table:
username
password
user_roles
user_id
default value
user_status
user_id
default value
i used pdo begin transaction stuff and commit stuff to make this work...
this worked great when I used it on just two tables, however when i decide to use another table and do the same code pattern, it did not work at all.
here are the codes:
$this->db->beginTransaction();
$sth = $this->db->prepare("INSERT INTO users (username, password)
VALUES (:user,:pass)");
$sth->execute(array(
':user'=> $data['user'],
':pass'=> Hash::create('sha256', $data['pass'], HASH)
));
$sth = $this->db->prepare("INSERT INTO user_role (user_id, role_id) VALUES (:user, :role)");
$sth->execute(array(
':user' => $this->db->lastInsertId(),
':role' => 3
));
$sth = $this->db->prepare("INSERT INTO user_status (user_id, status_id) VALUES (:user, :status)");
$sth->execute(array(
':user' => $this->db->lastInsertId(),
':status' => 1
));
$this->db->commit();
What do you think is the problem, I also doubt this is some kind of a syntax error, but I could not find, it, so my last resort is to ask, for I am not sure also if this works on 3 tables. Thank you!

after your first insert:
$insertID = $this->db->lastInsertId();
then in the following INSERTS
':user' => $insertID,

Related

How to insert value into FK column using PHP

Just a heads up, I'm quite new to this but I'd be really thankful if you can drop some knowledge.
I have SQL tables:
Table 'companies' which has the 'company_id' column as primary key.
Table 'users' which has the 'company_id' column as foreign key, referencing the 'companies' table, of course.
Upon signup, two types of users are created.
A manager - who also creates a company
A regular user - who joins the company
I want the regular user to have the company_id of the company he registered to. The user decides to which company he enrolls using a unique company_code.
The code looks like this, so far:
$sql = "SELECT company_id FROM companies WHERE company_code='$company_code';";
$result=mysqli_query($conn, $sql);
$row=mysqli_fetch_assoc($result);
$result=$row["company_id"];
$sql = "INSERT INTO users (firstName, lastName, email, user_uid, user_pwd, role, company_id) VALUES ('$first', '$last', '$email', '$uid', '$hashedPwd', '$role', '$result');";
mysqli_query($conn, $sql);
header("Location: ../signup.php?singup=success");
exit();
Everything seems to work just fine, but not the company_id column which is always NULL. Any idea what I'm doing wrong here?
I've already though about assigning the values of the last created user_id and the company_id that matches the company_code to variables and run a query similar to this:
UPDATE `users` SET `company_id` = '$company_id' WHERE `users`.`user_id` = $user_id;
but it really feels like over complicating my existence.
Thanks a lot!
You named your variable $result on line 4.
$result=$row["company_id"];
It should be:
$real_id = $row["company_id"];

INSERT Multiple Database Values To Specific Rows

How can I INSERT the values of this function to only WHERE the value of the username column (located in the login table, contains the exact same value as the value of the column nickname (located in a table called active_users).
$stmt = $this->pdo->prepare('INSERT INTO login (device_token) VALUES (?)');
$stmt->execute(array($token));
Additional info: when a user logs in, I set up the API to add the user's name to both username (in the login table) and nickname in the active_users table. Since these values will always be the same for their respective tables, I was hoping we could add some conditional logic to achieve this type of specificity. My goal is to take the device_token parameter and pass it to a different spot in the database.
Edit: Schema
Update AFNetworking command for login
NSMutableDictionary* params =[NSMutableDictionary dictionaryWithObjectsAndKeys:command, #"command", _nicknameTextField.text = fldUsername.text, #"username", hashedPassword, #"password", nil ];
Update: active_users INSERT statment
$stmt = $this->pdo->prepare('INSERT INTO active_users (user_Id, device_token, nickname, secret_code, ip_address) VALUES (?, ?, ?, ?, ?)');
$stmt->execute(array($userId, $token, $name, $code, $_SERVER['REMOTE_ADDR']));
If I understand you correctly. What you really want is an update and not an insert.
You want to add the value of device_token to the row with nickname, correct?
You would do that with an update:
UPDATE login
SET device_token = #token
WHERE username = #nickname
If you're trying to update the record with an existing record from active_users table than:
UPDATE login AS L
JOIN active_users AU ON L.username = AU.nickname
SET L.device_token = AU.device_token
Though, looking at your tables. I'm wondering if you're repeating too much of the data. It seems like you can link login and active_users by user_id. Well, this would get off topic, so I'll just suggest double checking db design concepts and your needs.
Using PDO it should be
UPDATE login
SET device_token = :token
WHERE username = :nickname
where the params array that will be bound looks like
$params = array("token" => $token, "nickname" => $nickname);
Full example:
$stmt = $this->pdo->prepare('UPDATE login SET device_token=:token WHERE nickname=:nickname');
$stmt->execute(array("token" => $token, "nickname" => $nickname));
Or you use the method of binding with ?
UPDATE login
SET device_token = ?
WHERE username = ?
where the parameter array is
$params = array($token, $nickname);
Full example:
$stmt = $this->pdo->prepare('UPDATE login SET device_token=? WHERE nickname=?');
$stmt->execute(array($token, $nickname));

MySQL INSERT INTO updates even if it shouldn't

My problem is that with a specific table in my database even if I use a simple INSERT INTO query the data gets updated instead of giving me a "Duplicate" error if the primary key already exists.
Structure of the table:
user_id (PRIMARY_KEY) | email (VARCHAR) | token (VARCHAR) | created (DATETIME)
If I excecute this:
$sql = "INSERT INTO
email_confirmation (
user_id,
email,
token,
created
) VALUES (
:user_id,
:email,
:token,
NOW()
)";
$query = $this->connection->prepare($sql);
$values = [
':user_id' => $customer['id'],
':email' => $customer['email'],
':token' => $token
];
$query->execute($values);
It will update my row instead of giving me an error if primary key already exists. Can anyone explain me why is this happening?

PHP/MySQL Using Variables and INSERT INTO syntax

I am trying to pass variable values to a MySQL database table. I am using a PDO to get access to the database, and am able to echo the variable values that I want to insert to my browser. The only thing I can think of is that my syntax is wrong. I am clearly a novice at using PHP/MySQL.
I am not getting any errors. The info isn't going into my table. What am I doing wrong?
$sql = "INSERT INTO testquiz (version, points, passing_percent, gained_score, username, email, quiz_title, date)
VALUES ('$version', $points, $passing_percent, $gained_score, '$username', '$email', '$quiz_title', CURDATE() )";
Query to create table:
MySQL CREATE TABLE Query:
CREATE TABLE testquiz (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
version TEXT,
points INT,
passing_percent DOUBLE,
gained_score DOUBLE,
username TEXT,
email TEXT,
quiz_title TEXT,
date DATE NOT NULL
) DEFAULTCHARACTER SET utf8 ENGINE=InnoDB
When using PDO, the generally accepted practice is to use prepared statements for SQL, which essentially are a method used to sanitize your string input.
If your database connection object is $dbo then it would usually go like this.
Create a prepared statement by calling the prepare method on your database connection object:
$sql = $dbo->prepare("INSERT INTO testquiz (version, points, passing_percent, gained_score, username, email, quiz_title, date)
VALUES (:version, :points, :passing_percent, :gained_score, :username, :email, :quiz_title, CURDATE())");
As you can see, instead of passing in the variables I want for the values directly, I've created placeholders. Then, call the execute method on the $sql obect and pass the values in for the placeholders as key-value pairs in an array.
$sql->execute(array(":version" => $version, ":points" => $points, ":passing_percent" => $passing_percent, ":gained_score" => $gained_score, ":username" => $username, ":email" => $email, ":quiz_title" => $quiz_title));
This code passes in the values you define instead of the placeholders, and it properly escapes and sanitizes the variables you pass in for security, while executing your INSERT statement.
http://us1.php.net/pdo.prepared-statements
Change the insert statement to the below format and try.
$sql = "INSERT INTO testquiz (version, points, passing_percent, gained_score, username, email, quiz_title, date)
VALUES ('".$version."', '".$points."', '".$passing_percent."', '".$gained_score."', '".$username."', '".$email."', '".$quiz_title."', CURDATE())";

Submitting data to two mysql tables using PDO

Is it possible to submit data to two tables with the same query?
My existing code looks like this:
private function adduser() {
if (!empty($this->error)) return false;
$params = array(
':user_level' => parent::getOption('default-level'),
':name' => $this->name,
':email' => $this->email,
':username' => $this->username,
':password' => parent::hashPassword($this->password)
);
parent::query("INSERT INTO `login_users` (`user_level`, `name`, `email`, `username`, `password`)
VALUES (:user_level, :name, :email, :username, :password);", $params);
I didn't write this code so it is a bit confusing to me as I don't usually use PDO. What I would like to do in addition to this is add two values to my 'url_alias' table, the first is the UID (which is auto incremented from the first query) and the second is another variable value.
All of the examples I have found while searching dont seem to work for me because of the way this existing code looks.
Can anyone give me a hand?
It doesn't matter what db driver your are using (PDO, Mysqli, etc.) you question is purely about mysql capabilities. Mysql may update and delete rows from multiple tables in a single query but not insert. I.e. INSERT table_1, table_2 ... is not allowed.
You have to run one query for each table you want to insert data.

Categories