Insert data on two tables using foreign key mysql php - php

Table user:
- user_id
- user_name
- (other info fields that doesn't matter for
Table item:
- item_id
- item_name
- (other info fields that doesn't matter for now)
All fields on the attached picture are from ITEM table but the last one that says "Colaborador"
Update:
Sorry,
The point is this:
I have 2 tables, Items and Users
And I want to register Electronic equipment on Items table (for example if I buy a cellphone I want to register it on that table) and then, that item (cellphone on this case) will be attributed to an user, and to do that register of the item attributed to the user I need to match the 2 tables with a foreign key that I already have, but the point is, I don't want to input the user_id (that is the foreign key), but I want to input the user NAME
Hope I make myself clear this time
PHP Code
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO ativos (item,comentario,data_aquisicao,localizacao,fabricante,modelo,anexo_a,numero_serie,imei,ativo_sap,evento,data_entrega,data_devolucao,data_estravio,id_user) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($item,$comentario,$data_aquisicao,$localizacao,$fabricante,$modelo,$anexo_a,$numero_serie,$imei,$ativo_sap,$evento,$data_entrega,$data_devolucao,$data_estravio,$id_user));
Database::disconnect();
header("Location: index.php");
}

Without seeing how your PHP code generates your associated MySQL queries, we can't possibly tell you how to re-factor your specific case to achieve this functionality.
On a more generic level, you'd probably have to pass the username from the input form into a subquery as part of your INSERT statement:
INSERT INTO `item` (item_id, item_name, owner_id)
VALUES (1, 'abcdef', (SELECT user_id FROM user WHERE user_name = 'user1'))
Edit after OP edit to add PHP code:
Just refactor your $sql string query to include the subquery:
$sql = "INSERT INTO ativos (item,comentario,data_aquisicao,localizacao,fabricante,modelo,anexo_a,numero_serie,imei,ativo_sap,evento,data_entrega,data_devolucao,data_estravio,id_user) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT user_id FROM user WHERE user_name = ?))";
... which should return the user_id associated with a particular user_name and insert the ID value to the record.

Related

SQL return multiple tables

I am using PHP and MySQL
Let's say i have a query like
SELECT * FROM tablename WHERE smth=?
And i need to perform 10 of this queries on the same table, each with different 'smth' value.
Can i make SQL return multiple tables in one run, each for it's 'smth' value?
Use IN:
SELECT *
FROM tablename
WHERE smth IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
You can pass all ten values in as parameters.

Update already existing values while adding new ones

I'm inserting some values into my database.
$stmt = $conn->prepare("INSERT INTO `members` (`id`, `name`, `nickname`, `prefix`, `suffix`) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss",$row['member_id'], $row['name'], $row['nickname'], $row['prefix'], $row['suffix']);
$stmt->execute();
This does what I want: if a new user has joined this will add them to members. However, if an already existing member has changed their nickname this info doesn't get updated. I would like to 1) add new members like it currently does but also 2) update the nicknames for already existing members if there are any changes.
I tried adding the following code after the one above (first add members and then update) but it doesn't seem to work as I wanted.
$stmt = $conn->prepare("UPDATE members SET nickname = '?' WHERE id = '?'");
$stmt->bind_param("ss",$row['nickname'], $row['id']);
$stmt->execute();
You can use REPLACE INTO instead of INSERT INTO
Your prepare() would have
REPLACE INTO `members` (`id`, `name`, `nickname`, `prefix`, `suffix`) VALUES (?, ?, ?, ?, ?)
REPLACE updates the new data if the primary key value already exists.
More details here: https://dev.mysql.com/doc/refman/5.5/en/replace.html

Codeigniter Insert with Select Query

Is there a way to make this Query work in MySQL Codeigniter
Basically is make a select inside a Insert to avoid double Query
I want to make an INSERT a row in a table called recibos_nomina but the field recibos_nomina.id_usuario is one a table called usuarios i have usuarios.rfc and i want to nest SELECT id FROM usuarios WHERE rfc = XXX to get the id and insert in recibos_nomina.id_usuario with one Query only, this is possible with MySQL but i don't know how to make it with codeigniter.
$this->db->trans_begin();
$this->db->query('insert into recibos_nomina(id_empresa, id_usuario, fecha, folio, total, uuid, url_xml, temporal, folio_fiscal, fechahora_certificado, csd_sat, sello_cfd, sello_sat, sello)
values(?, (SELECT id FROM usuarios WHERE rfc = ?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', array(
2,
//intval($this->post('id_empleado')),
$recibo->usuario->rfc,
date("Y-m-d"),
$recibo->folio,
$recibo->total,
$recibo->uuid,
$recibo->url_xml,
1,
$recibo->uuid,
//str_replace("T", " ", $recibo->fecha),
$recibo->fecha,
$recibo->csd_sat,
$recibo->sello_cfd,
$recibo->sello_sat,
$recibo->sello_cfd
));
$id_recibo = $this->db->insert_id();

Issue On Inserting Auto Incremented ID in MySQL Using Prepared Statement

I have table in MySQL database called MyGuests which has 4 fields as : id (PK and Auto Increment), name,age and email. I am using following code to insert data from user input form to the database:
<?php
$sql = mysqli('localhost','user','password','database');
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
$query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (?, ?, ?, ?)");
$query->bind_param("isis",$name,$age,$email);
$query->execute();
?>
now I am confused how to insert value for id which is auto incremented field using the Prepared statement! As you can see I passed 4 parameters as (?, ?, ?, ?) for data entry and used the "isis" for bind_param(); but not sure what must put in $name,$age,$email for id?
Can you please help me to figure this out?
Thanks
Just omit the id in the query i.e.
INSERT INTO MyGuests ( name, age, email) VALUES (?, ?, ?)
It will automatically add the incremented id, hence the name :)
one more option is supplying null value to the auto-increment column:
ie.
instead of $query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (?, ?, ?, ?)"); use $query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (null, ?, ?, ?)");

Update all values except auto-increment field using PHP / MySql / PDO

I have a quick question...I am updating all values in a row using a prepared statement and an array.
When initially inserting, my statement looks like this (and works perfect)
$sql="INSERT INTO $dbtable VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
The first and last values are NULL as the first is an auto increment ID field and last is a timestamp field.
Is there a way to keep my UPDATE statement as simple as my INSERT statement like this...
$sql="UPDATE $dbtable SET (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) WHERE `announcements`.`id` = $id LIMIT 1";
I realize this does not work as is due to the first value being an auto increment field, is there a value I could put into my array to 'skip' this field?
This may not be the best way to describe my question but if you need more info, please let me know!
Thank you in advance!
UPDATE has no "implicit columns" syntax like INSERT does. You have to name all the columns that you want to change.
One alternative you can use in MySQL is REPLACE:
REPLACE INTO $dbtable VALUES (?, ?, ?, ?, ?, ...)
That way you can pass the current value for your primary key, and change the values of other columns.
Read more about REPLACE here: https://dev.mysql.com/doc/refman/5.6/en/replace.html
Note that this is internally very similar to #Devon's suggestion of using two statements, a DELETE followed by an INSERT. For example, when you run REPLACE, if you have triggers, both the ON DELETE triggers are activated, and then the ON INSERT triggers. It also has side-effects on foreign keys.
The solution I can think of doesn't involve an UPDATE at all.
DELETE FROM $dbtable WHERE id = $id;
INSERT INTO $dbtable VALUES ($id, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
Since you don't want to use the UPDATE syntax, this would delete the row and add a new row with the same id, essentially updating it. I would recommend wrapping it in a transaction so you don't lose your previous row if the insert fails for any reason.

Categories