MySQL INSERT INTO updates even if it shouldn't - php

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?

Related

SQL: Auto insert the a value from another table

I have two tables the first one is "student":
id (PK) "auto_inc"
student_name
email
The second one is "bill":
id (PK) "auto_inc"
student_id (FK -> id)
total_balance
I am trying to auto-insert the last 'id' into 'student_id' when I add a new student in the same query.
This is my query to add a new student to the table
insert into student (name, major, emailAddress)
values ( :name, :major, :emailAddress )
For example:
id= 1
student_name= "Mike"
email= "mike#mail.com"
bill table:
id= 1
student_id= 1 "from 'student' table"
total_balance= 100
I do not have much experience with SQL DB, I am recently using it.
I can advice next approach:
create table student with unique key email
create table student (
id int primary key auto_increment,
student_name varchar(255),
email varchar(255) unique key
);
use next PHP code:
<?php
$name = "Barry Block";
$email = "barry.b#gmail.com";
$balance = 500;
$student_sql = "
insert into student (student_name, email)
values ( :name, :emailAddress )";
$stmt = $pdo->prepare($student_sql);
$stmt->execute([':name'=>$name, ':emailAddress'=>$email]);
$bill_sql = "
insert into bill (student_id, total_balance)
select id, :balance from student where email = :emailAddress";
$stmt = $pdo->prepare($bill_sql);
$stmt->execute([':balance'=>$balance, ':emailAddress'=>$email]);
Test MySQL & PHP code online

if id exist use on duplicate key, else insert

I have a database with following table test_users:
| id | Username | Password |
| 1 | pat | ***** |
| 2 | roger | ***** |
| 3 | luke93 | ***** |
And to insert a new row I use following code, and it works fine:
$sql = $conn->prepare("INSERT INTO `test_users` (`Username`, `Password`) VALUES (?,?)");
$sql->bind_param('ss',$name, $email);
But now i am trying to make a "update profile"-page and I wanted to use ON DUPLICATE KEY. That means I need to check if idexists and if so update the row. Neither Username or Password is Unique, but id is. I have a $_SESSION["id"] which is available if the user is logged in. Can I use that in some way?
So how do I write a SQL-sentence that finds out if id exist, and if so, overwrite it with ON DUPLICATE KEY (or a better way)?
first write selct query and count num rows if its 0 then insert query fire else update query
UPDATE works the same as an insert. You just need to pass the WHERE condition.
You can do this with the following code, Try it
$id = $_SESSION['id'];
$sql = "UPDATE test_users SET Username=?, Password=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param($Username, $Password, $id);
$stmt->execute();
Assign unique key of your unique field and try below query
Insert into a MySQL table or update if exists
INSERT INTO test_user(id, username, password) VALUES(1, "test", "test") ON DUPLICATE KEY UPDATE
username="test", password="test"
Use INSERT ... ON DUPLICATE KEY UPDATE
QUERY:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name="A", age=19
credits to Donnie

Can not set a NOW() in datetime field mysql with php

Hello I'm having a hard time trying to update this field automatically when I update something else in that same table called 'reps' the structure of the table is:
id int primary key,
name varchar(10) not null,
date_up datetime
When I run this query:
SELECT * FROM reps;
it shows the information correctly however when I try to update a row of this table the date_up field is not updating... here's my code:
require dirname(__FILE__).'/db/connect.php';
$id = 5;
$name = "LCD Replacement";
$conexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $conexion->prepare('UPDATE reps SET name=:name, date_up = NOW() WHERE id = :id');
$statement->execute(array(
':name' => $name,
':id' => $id
));
when I refresh the page nothing is updated but if I run that same SQL query on the mysql console it work so I don't know what I'm doing wrong??

Concatenating a string and primary key Id while inserting

I have a user table in mysql, I insert data like this:
/* prepare query */
$query = 'INSERT INTO `users`(`first_name`,
`last_name`,
`gender`,
`username`,
`profile_picture`,
`provider`,
`provider_id`,
`provider_username`,
`provider_profile`,
`provider_profile_picture`,
`last_login`,
`created_date`,
`ip_address`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW(), INET_ATON(?))';
/* Prepare an insert statement */
$stmt = $mysqli->prepare($query);
if($stmt){
$stmt->bind_param("sssssssssss", $user['first_name'],
$user['last_name'],
$user['gender'],
$user['username'],
$user['profile_picture'],
$user['provider'],
$user['id'],
$user['username'],
$user['link'],
$user['profile_picture'],
$_SERVER['REMOTE_ADDR']);
$stmt->execute();
/* Execute the statement */
I would like to make the username be equal to 'user' + userId which is autoincremental primary key field.
so that the usernames get in order:
user1
user2
user3 and so forth
what is a slick way to accomplish that?
If user_id is an AUTO_INCREMENT primary key, then you can't do this with a single statement, even if you use a trigger.
The problem is that the AUTO_INCREMENT value isn't generated until after the BEFORE INSERT trigger runs, but you can't change username in the AFTER INSERT trigger.
So you just have to do the INSERT, then immediately do an UPDATE.
If user_id is not an AUTO_INCREMENT, but instead is something you specify yourself, then it's easy, you just do the concatenation in your PHP code before you pass the values as parameters.
Update: You can't do it with MySQL 5.7 generated columns either. It results in this error when you try to create the table:
Generated column 'username' cannot refer to auto-increment column.
Assuming the username is always 'user' + userid, the slickest way I can think of to do this is to have a table with everything except username in it, and a view on top of that table that adds username. You would then do any inserts and updates on the table, and any selects that require username could be done on the view.
CREATE VIEW userview AS
SELECT user_id, first_name, last_name, gender, profile_picture, provider,
provider_id, provider_username, provider_profile, provider_profile_picture,
last_login, created_date, ip_address, 'user' + user_id as username
FROM USER

Using LastInsertId Multiple times, PHP PDO

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,

Categories