Check if value exist in Mysql Database on PHP - 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.

Related

Update foreign key with other field 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
}
?>

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.

Fields not entered into mysql database in phpmailer script

I am editing a pre-made script for iDEAL payments which is available here. What I’m trying to do is add a few fields to the form and database. The extra fields show up fine in the email template, but they are not entered into the database. The script works with PHPmailer.
I think this is where the problem is:
$stmt = $db->prepare("INSERT INTO tbl_ideal_payments SET
ID = ?, datumtijd = NOW(),
naamfrom = ?, emailfrom = ?,
naamto = ?, emailto = ?,
bedrag = ?, descr = ?,
mailsubject = ?, mailtekst = ?,
ipadres = ?,
heenreis = ?,
terugreis = ?,
postcode = ?,
factuurnummer = ?,
status = 'open'");
//var_dump($stmt);
$stmt->bind_param('sssssdssss', $session, $naamfrom, $emailfrom, $contact, $emailto, $bedrag, $paydecr, $subject, $mailmsg, $heenreis, $terugreis, $postcode, $factuurnummer, $_SERVER['REMOTE_ADDR']);
The fields that I'm trying to add are heenreis, terugreis, postcode, and factuurnummer.
Full code for the config, form, and above script can be found here (seems a bit much to paste in this post).
What am I doing wrong?
Count the data type parameters 'sssssdssss' and then count the parameters place holders ?, and then count the columns in the SET clause, they should all be the same number.
Also this situation will have generated an error, but you are not testing for errors
While developing, specially if you are developing on a LIVE server where error reporting should be turned off add these lines at the top of the script, to turn on error reporting.
<?php
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
// if you are using the MYSQLI_ database extension add this also
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $db->prepare("INSERT INTO tbl_ideal_payments SET
ID = ?, datumtijd = NOW(),
naamfrom = ?, emailfrom = ?,
naamto = ?, emailto = ?,
bedrag = ?, descr = ?,
mailsubject = ?, mailtekst = ?,
ipadres = ?,
heenreis = ?,
terugreis = ?,
postcode = ?,
factuurnummer = ?,
status = 'open'");
// also add error test
if ( !$stmt ) {
echo $db->error;
exit;
}
// now add the 4 missing data type parameters
// I have assumed they are all string !!!
// You should check with your schema what datatype they actually are
$stmt->bind_param('sssssdssssssss', $session,
$naamfrom,
$emailfrom,
$contact,
$emailto,
$bedrag,
$paydecr,
$subject,
$mailmsg,
$heenreis,
$terugreis,
$postcode,
$factuurnummer,
$_SERVER['REMOTE_ADDR']
);

How to fix stmt prepare and bind

I am having trouble using this prepare and bind. I have tried the same thing with less variables to bind. I have been successful using prepare with just Fname, Lname, Password, $UserID and using sssi with the bind_param object. Can someone explain what I am doing wrong when using more variables in my bind code? With the code below it only prints out the same data from mysqli and doesn't update it.
if ($stmt = $con->prepare("UPDATE users SET Fname = ?, Lname = ?, Password = ?, UserLevel = ?, Email = ?, WHERE UserID= ?"))
{
$stmt->bind_param("ssssssi", $firstname, $lastname, $PW, $UserLevel, $EM, $UserID);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: admin.php");
Although you haven't specified the data types which makes this tricky, I'll hazard a guess.
Fname = s
Lname = s
Password = s
UserLevel = i (?)
Email = s
I count 4 s' there, yet you have 6.
Try this,
$stmt->bind_param("sssisi", $firstname, $lastname, $PW, $UserLevel, $EM, $UserID);
Edit 1
As #Fred-ii- said, your SQL query is wrong.
Change
"UPDATE users SET Fname = ?, Lname = ?, Password = ?, UserLevel = ?, Email = ?, WHERE UserID= ?"
to,
"UPDATE users SET Fname = ?, Lname = ?, Password = ?, UserLevel = ?, Email = ? WHERE UserID= ?"
You had a training ,.

Correct Syntax For Preparing MySQL INSERT INTO ON DUPLICATE KEY UPDATE?

I have been troubleshooting my code, searching stackoverflow to find the correct syntax to do this with PHP. I can't figure out how the ON DUPLICATE KEY UPDATE syntax works with prepared statements:
INSERT INTO placements_by_date (DateVal, PlacementName, PlacementId,
CampaignId, AdName, Format, TagId, Impressions, Clicks, Leads, MediaCost)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
// HERE COMES THE TRICKY SYNTAX:
DateVal = VALUES(DateVal), PlacementName = VALUES(PlacementName),
PlacementId = VALUES(PlacementId), CampaignId = VALUES(CampaignId),
AdName = VALUES(AdName), Format = VALUES(Format), TagId = VALUES(TagId),
Impressions = ?, Clicks = ?, Leads = ?, MediaCost = ?
I have tried many variations:
...ON DUPLICATE KEY UPDATE
DateVal = VALUES('$DateVal'), PlacementName = VALUES('$PlacementName'),
PlacementId = VALUES('$PlacementId'), CampaignId = VALUES('$CampaignId'),
AdName = VALUES('$AdName'), Format = VALUES('$Format'), TagId = VALUES('$TagId'),
Impressions = VALUES(?), Clicks = VALUES(?), Leads = VALUES(?),
MediaCost = VALUES(?)";
I store this as a string, $sql, and do my usual stuff:
$mysqli = new mysqli(...
...
$stmt = $mysqli -> prepare($sql);
$stmt -> bind_param('sissiiiis', $PlacementName, $PlacementId,
$AdName, $Format, $TagId, $Impressions,
$Clicks, $Leads, $MediaCost);
...
But maybe the parameters should be bound differently??
I enabled tried reading through the feedback but this was too generic with no actionable insights.
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;
Hoping you have some insight to share?
Thanks!
Why not continue using the VALUES() method?
INSERT INTO placements_by_date(DateVal, PlacementName, PlacementId,
CampaignId, AdName, Format, TagId,
Impressions, Clicks, Leads, MediaCost
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
DateVal = VALUES(DateVal), PlacementName = VALUES(PlacementName),
PlacementId = VALUES(PlacementId), CampaignId = VALUES(CampaignId),
AdName = VALUES(AdName), Format = VALUES(Format), TagId = VALUES(TagId),
Impressions = VALUES(Impressions), Clicks = VALUES(Clicks), Leads = VALUES(Leads),
MediaCost = VALUES(MediaCost);
You don't specify what the unique key is. However, you don't need to include those columns in the update statements, because they are already the same.
If, perchance, you want to increment the last four values rather than just assign them, you can do that too:
ON DUPLICATE KEY UPDATE
DateVal = VALUES(DateVal), PlacementName = VALUES(PlacementName),
PlacementId = VALUES(PlacementId), CampaignId = VALUES(CampaignId),
AdName = VALUES(AdName), Format = VALUES(Format), TagId = VALUES(TagId),
Impressions = Impressions + VALUES(Impressions),
Clicks = Clicks + VALUES(Clicks),
Leads = Leads + VALUES(Leads),
MediaCost = MediaCost + VALUES(MediaCost)
EDIT:
The following should work just to update the last four columns:
INSERT INTO placements_by_date(DateVal, PlacementName, PlacementId,
CampaignId, AdName, Format, TagId,
Impressions, Clicks, Leads, MediaCost
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
Impressions = VALUES(Impressions), Clicks = VALUES(Clicks), Leads = VALUES(Leads),
MediaCost = VALUES(MediaCost);

Categories