Update foreign key with other field PHP - php

I have a php page where I can Create, Update and see some users and other page where I can see the user's(colaboradores's table) items(ativos's table) and they are linked with an FK(id_colaborador).
On the ativos create page, I manage to input all the data and instead of input the FK itselv (id_colaborador) the user can input the NAME of the user (colaboradores.nome).
The point is, I want to do the same thing on the UPDATE.PHP page, but I just can't figure it out how to input the colaboradores.nome on the id.colaborador (FK) field instead of it...
Sorry if I couldn't explain myself clearly.
Here's the $sql var with the query for create.php:
$sql = "INSERT INTO ativos (ativo,comentario,data_aquisicao,localizacao,fabricante,modelo,imei,
numero_serie,ativo_sap,evento,data_evento,id_colaborador)
SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, id_colaborador
FROM colaboradores
WHERE nome = ?";
And here's the $sql var with the query for update.php:
$sql = "UPDATE ativos SET ativo = ?, comentario = ?, data_aquisicao = ?, localizacao = ?, fabricante = ?, modelo = ?, imei = ?,
numero_serie = ?, ativo_sap = ?, anexo_a = ?, evento = ?, data_evento = ?, id_colaborador = ? WHERE id_ativo = ?";
Thank you for you time!
Update:
I mean, is it possible to get the update code similiar to the create code?
Update must select the colaboradores.nome to replace id.colaborador (FK) and keep the WHERE id_ativo = ? something like that i gues...
$sql = "UPDATE ativos SET ativo = ?, comentario = ?, data_aquisicao = ?, localizacao = ?, fabricante = ?, modelo = ?, imei = ?,
numero_serie = ?, ativo_sap = ?, anexo_a = ?, evento = ?, data_evento = ? SELECT id_colaborador FROM colaboradores
WHERE nome = ? AND WHERE id_ativo = ?";

You need to generate a list with PHP (e.g. dropdown) containing name as label and id as value.
So users will be able to select in a list of name. When selection is made, you have to use the value (id).
<form action="#" method="post">
<select name="Users">
<option value="1">Paul</option>
<option value="2">Pierre</option>
<option value="5">Marco</option>
<option value="8">Jean</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
Then retreive id with PHP
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['Users']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; // Displaying Selected Value
}
?>

Related

Check if value exist in Mysql Database on PHP

When I'm updating an item (ativo) of an employee (colaborador) I need to check if an employee that the user input exists or not in the DB, and if it doesn't - give an error message. I don't know how can I do it, can you guys point me to some tutorial that explains it? Thanks in advance!
This is my query btw:
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE ativos SET ativo = ?, comentario = ?, data_aquisicao = ?,
localizacao = ?, fabricante = ?, modelo = ?,
imei = ?, numero_serie = ?, ativo_sap = ?,
anexo_a = ?, evento = ?, data_evento = ?,
id_colaborador = (SELECT id_colaborador
FROM colaboradores
WHERE nome = ?
LIMIT 1
)
WHERE id_ativo = ?";
$q = $pdo->prepare($sql);
$q->execute(array($ativo,$comentario,$data_aquisicao,$localizacao,
$fabricante,$modelo,$imei,$numero_serie,$ativo_sap,
$anexo_a,$evento,$data_evento,$id_colaborador,$id));
And this is the input (i don't know if it's needed to validate if the row exist)
<input autocomplete="off" name="id_colaborador" type="text" placeholder="Nome do Colaborador" value="<?php echo !empty($nome)?$nome:'';?>" class='auto'>
Your query is not considering the possibility of homonyms. So, you'd better use some auto_complete field to get the 'id_colaborador' based on the name and keep it in a hidden input field and then execute the update with the exact values.

UPDATE with multiple WHERE and SELECT condition - MySql

So, I have two tables ativos and colaboradores and they are linked by id_colaborador (FK) on my update page, I'm able to change the id_colaborador but instead of changing the ID I want to write the name that match to that ID but I think I need multiple WHERE conditions and SELECT, may anyone help me out? Thanks!
I have the following code to update
$sql = "UPDATE ativos SET ativo = ?, comentario = ?, data_aquisicao = ?, localizacao = ?, fabricante = ?, modelo = ?, imei = ?,
numero_serie = ?, ativo_sap = ?, anexo_a = ?, evento = ?, data_evento = ?, SELECT id_colaborador FROM colaboradores WHERE nome = ? AND WHERE id_ativo = ?";
UPDATE
I've already try to separete the two statements like this:
$sql = "UPDATE ativos SET ativo = ?, comentario = ?, data_aquisicao = ?, localizacao = ?, fabricante = ?, modelo = ?, imei = ?,
numero_serie = ?, ativo_sap = ?, anexo_a = ?, evento = ?, data_evento = ?, id_colaborador = ? WHERE id_ativo = ?";
$sql2 = "SELECT id_colaborador FROM colaboradores WHERE nome = ?";
$q = $pdo->prepare($sql,$sql2);
But it gives me the following error:
Warning: PDO::prepare() expects parameter 2 to be array, string given in C:\xampp\htdocs\gestao\Colaboradores\ativo_update.php on line 120
Fatal error: Uncaught Error: Call to a member function execute() on boolean in C:\xampp\htdocs\gestao\Colaboradores\ativo_update.php:121 Stack trace: #0 {main} thrown in C:\xampp\htdocs\gestao\Colaboradores\ativo_update.php on line 121
You can use sub-query as i understand that you want to update by name which name not in the same table ok you can check query bellow :
$sql = "UPDATE ativos SET ativo = ?, comentario = ?, data_aquisicao = ?, localizacao = ?, fabricante = ?, modelo = ?, imei = ?,
numero_serie = ?, ativo_sap = ?, anexo_a = ?, evento = ?, data_evento = ? WHERE id_colaborador in (SELECT id_colaborador FROM colaboradores WHERE nome = ?) and id_ativo = ?";
#ADyson have solution in comment which update the id_colaborador too by name :
$sql = "UPDATE ativos SET ativo = ?, comentario = ?, data_aquisicao = ?, localizacao = ?, fabricante = ?, modelo = ?, imei = ?, numero_serie = ?, ativo_sap = ?, anexo_a = ?, evento = ?, data_evento = ?, id_colabarador = (SELECT id_colaborador FROM colaboradores WHERE nome = ? LIMIT 1) WHERE id_ativo = ?";
This query will allow you to update the id_colabarador in the ativos table based on a name being input from the form:
$sql = "UPDATE ativos SET ativo = ?, comentario = ?, data_aquisicao = ?, localizacao = ?, fabricante = ?, modelo = ?, imei = ?, numero_serie = ?, ativo_sap = ?, anexo_a = ?, evento = ?, data_evento = ?, id_colabarador = (SELECT id_colaborador FROM colaboradores WHERE nome = ? LIMIT 1) WHERE id_ativo = ?";
Note though that if the names are not unique in the colabarador table, there's a chance it may return the wrong ID by accident.
As mentioned in the comments though, I highly recommend that instead you re-design the GUI so that the user can select using the name, but that in the background this stores the ID related to the selected record, so that the ID can be passed directly from the form to the PHP, and then be used in the SQL in place of the sub-query. This will be more robust and doesn't leave you open to accidental mis-identification of the record.

Insert foreign key with other field

so I've try to insert data on PHP CRUD with foreign key but instead of input the number (which is the FK) I want to input an NAME
I have the following code:
// Inserir os dados
if ($valid) {
$pdo = Dat abase::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO ativos (ativo,comentario,data_aquisicao,localizacao,fabricante,modelo,imei,numero_serie,ativo_sap,anexo_a,evento,data_evento,id_colaborador) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($ativo,$comentario,$data_aquisicao,$localizacao,$fabricante,$modelo,$imei,$numero_serie,$ativo_sap,$anexo_a,$evento,$data_evento,$id_colaborador));
Database::disconnect();
header("Location: index.php");
}
}
And I've already tried this but it won't work
if ($valid) {
$pdo = Dat abase::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO ativos (ativo,comentario,data_aquisicao,localizacao,fabricante,modelo,imei,numero_serie,ativo_sap,anexo_a,evento,data_evento,id_colaborador) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? (SELECT id_colaborador FROM colaboradores WHERE nome = ?))";
$q = $pdo->prepare($sql);
$q->execute(array($ativo,$comentario,$data_aquisicao,$localizacao,$fabricante,$modelo,$imei,$numero_serie,$ativo_sap,$anexo_a,$evento,$data_evento,$id_colaborador));
Database::disconnect();
header("Location: index.php");
}
Note
id_colaborador is the foreign key
You would be better off passing in the ID, but if you need to use a NAME, then the format of your INSERT needs to be changed slightly (see INSERT ... SELECT...) ...
INSERT INTO ativos (ativo,comentario,data_aquisicao,localizacao,fabricante,modelo,imei,
numero_serie,ativo_sap,anexo_a,evento,data_evento,id_colaborador)
SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, id_colaborador
FROM colaboradores
WHERE nome = ?
So the SELECT has all of the parameters as values and then it just selects the ID (id_colaborador) from the other table.

Insert statement with variables failing

new here
I've come across this problem.
It doesn't seem to be able to use my id's from the two first statements in my last statements as a variable resource, so the sqlcharacter statement fails.
What do i do wrong?
$sqlimg = ("INSERT INTO cimages(image) VALUES(?)");
$stmtimg = $conn->prepare($sqlimg);
$stmtimg->bind_param('s', $image);
$stmtimg->execute();
$img_id = $stmtimg->insert_id;
// I insert the picture first, and retrieve it's ID
$sqlstats = ("INSERT INTO cstats(Strength, Dexterity, Constitution,
Intelligence, Wisdom, Charisma, Aligment) VALUES(?, ?, ?, ?, ?, ?, ?)");
$stmtstats = $conn->prepare($sqlstats);
$stmtstats->bind_param("iiiiiis", $strength, $dexterity, $constitution,
$intelligence, $wisdom, $charisma, $aligment);
$stmtstats->execute();
$stats_id = $stmtstats->insert_id;
// I insert the characters stats, and retrieve it's ID
// Last I insert The user_id and img_id and stats_id
$user_id = mysqli_real_escape_string($conn, $_POST['user_id']);
// I've used the session id to get the user_id already
$sqlcharacter = ("INSERT INTO characters(Cname, Clast, Crace, house,
location, Bgstory, user_id, img_id, stats_id) VALUES(?, ?, ?, ?, ?, ?, ?,
$img_id, $stats_id)");
$stmtChar = $conn->prepare($sqlcharacter);
$stmtChar->bind_param('ssssssiii', $Cname, $Clast, $Crace, $house,
$location, $Bgstory, $user_id, $img_id, $stats_id);
$stmtChar->execute();
The $sqlcharacter string looks like you've got two variables $img_id and $stats_id in there instead of ?, so I think that's why it's not binding those values.
Try changing this:
"INSERT INTO characters(Cname, Clast, Crace, house,
location, Bgstory, user_id, img_id, stats_id) VALUES(?, ?, ?, ?, ?, ?, ?,
$img_id, $stats_id)"
To this:
"INSERT INTO characters(Cname, Clast, Crace, house,
location, Bgstory, user_id, img_id, stats_id) VALUES(?, ?, ?, ?, ?, ?, ?,
?, ?)"

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']);

Categories