Update already existing values while adding new ones - php

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

Related

Insert data on two tables using foreign key mysql 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.

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();

php on duplicate key

I'm having trouble trying to get the following to work:
$stmt = $mysqli->prepare("INSERT INTO member_data (member_id, name, address, telephone, mobile) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE member_data SET name = ?, address = ?, telephone = ?, mobile = ? WHERE member_id = ?");
$stmt->bind_param('ssssssssss', $_SESSION['user_id'], $_POST['new_name'], $_POST['new_address'], $_POST['new_telephone'], $_POST['new_mobile'], $_POST['new_name'], $_POST['new_address'], $_POST['new_telephone'], $_POST['new_mobile'], $_SESSION['user_id']);
$stmt->execute();
$stmt->close();
It doesn't seem to be able to update or insert any values.
I'm sure I've done something wrong, but I've searched and haven't found anything relevant to my issue. Is this the right approach?
EDIT: Working code:
$stmt = $mysqli->prepare("INSERT INTO member_data (member_id, name, address, telephone, mobile) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE name = ?, address = ?, telephone = ?, mobile = ?");
$stmt->bind_param('sssssssss', $_SESSION['user_id'], $_POST['new_name'], $_POST['new_address'], $_POST['new_telephone'], $_POST['new_mobile'], $_POST['new_name'], $_POST['new_address'], $_POST['new_telephone'], $_POST['new_mobile']);

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, ?, ?, ?)");

Insert auto-incremented ID using prepared statements

When inserting a new record into a table with an auto-incrementing ID column, it is normally enough to give the ID field the value NULL or omit it from the INSERT query, as explained at How to insert new auto increment ID
INSERT INTO `database`.`table` (`id`, `user`, `result`) VALUES (NULL, 'Alice', 'green')");
or
INSERT INTO `database`.`table` (`user`, `result`) VALUES ('Alice', 'green')");
My question is - how do you do the same thing when using prepared statements. I have tried the following, using NULL:
$stmt = $db->prepare("INSERT INTO `db` (id, name, password, text) VALUES (NULL, ?, ?, ?)");
$stmt->bind_param('sss', $name, $password, $text);
$stmt->execute();
and the fowllowing, omitting the ID field:
$stmt = $db->prepare("INSERT INTO `test_db` (name, password, text) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $name, $password, $text);
$stmt->execute();
When I run this I get nothing inserted and no error message in the browser. I think it is because it is trying to insert a duplicate value for the ID field (stackoverflow.com/questions/12179770/…) - but why it should do that when this seems equivalent to the non-prepared-statement way of inserting data, and then give no message, I'm not sure.
Any ideas most welcome!

Categories