I have a table with input of type time and I want to check first if there is a row with the current date and the id of employee, if it was I update the value of the input if not I insert a new row. This is what I have tried but it always inserts a new row even if the condition exists:
<?php
$E1=$_POST['E1'];
$connect = mysqli_connect("localhost", "root", "ntr-ktb123", "absence");
$sql1="SELECT * FROM retards WHERE Date ='Curdate()' AND
IdEmpl='".$_POST["IdEmp"]."' ;";
$result1=mysqli_query($connect,$sql1);
if(!$result1){
die('ERREUR SQL ! <br>'.$sql.'<br>'.mysqli_error());}
if($dt=mysqli_fetch_array($result1,MYSQLI_ASSOC)){
$sql="update retards set E1='$E1' where IdEmpl='".$_POST["IdEmp"]."' AND
Date=CURDATE();";
}
else{
$sql="insert into retards(IdEmpl,Date,E1) values
('".$_POST["IdEmp"]."',CURDATE(),'$E1'); ";
}
$result = mysqli_query($connect, $sql);
if (!$result)
{
echo("Error description: " . mysqli_error($connect));
}
else {
$message ="Effectué avec succès!";
echo "<script type='text/javascript'>alert('$message'); </script>";
}
mysqli_close($connect);
?>
This is known as an upsert which can be done in mysql using the insert ... on duplicate key update syntax.
insert into t (a, b, c) values (?, ?, ?)
on duplicate key update b = ?
Your table should have an appropriate unique index or primary key defined on the column(s) of interest.
Related
How should i solve this? there is not a row 1 and i cant insert or update data. Unique keys are indeed ip and uid in my table.
My code is as follows:
//Retrive listeners per reload
echo 'Data Höganäs <br>';
$sc="http://USER:PWD#SUB.SERVER.se:10000/admin.cgi?sid=1&mode=viewxml&page=3";
$xml2 = simplexml_load_file($sc);
foreach ($xml2->LISTENERS->LISTENER as $listener2) {
// Create connection
$conn = new mysqli($host, $user, $pwd, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = " insert INTO hoganaskey
(ip, uid, tid, starttid, date)
VALUES
('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT', '$starttid', '$date')
on duplicate key
update tid='$listener2->CONNECTTIME' ";
//$sql = "INSERT INTO hoganaskey (ip, uid, tid, ua, starttid, date) VALUES('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT' '$starttid', '$date') ON DUPLICATE KEY UPDATE tid='$listener2->CONNECTTIME' ";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
} //End foreach SHOUcast listener
Im returning this error in insert "Column count doesn't match value count at row 1".
In your insert query, you listed only 5 field names:
(ip, uid, tid, starttid, date)
but you are passing 6 values not 5:
('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT', '$starttid', '$date')
I have a table with columns userID(int),timeIN(date),timeOUT(date)
I am inserting a record in mysql database. First I check if the userID is correct from the other table and if its correct it will add a new record of the userID and timeIN(date) whereas the timeOUT will be NULL, else it will display error if the userID is not correct. I want my code to be able to check if the user is currently timeIN so it will prevent a double entry. I would also like to insert or update timeOUT(date) if the values of userID is equals to the user input and timeIN is not null and timeOUT is null.
Please kindly help...thanks.
Here is my code for inserting userID and timeIN: IT WORKS when inserting into mysql database.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
require_once('dbConnect.php');
$userID = $_POST['userID'];
$sql = "SELECT * FROM employee WHERE userID='$userID'";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);
if(isset($check)){
$sql = "INSERT INTO dtr (userID,timeIN) VALUES ('$userID', now())";
mysqli_query($con, $sql);
echo 'Time IN Successful!';
}else{
echo 'Invalid USER ID. Please try again!';
}
mysqli_close($con);
}
?>
You should handle these checks inside the database. The current check you are doing in the database can be handled by a foreign key constraint:
alter table dtr add constraint fk_dtr_userId
foreign key (userId) references employee(userId);
The second means that you want only one row with a NULl value. Ideally, this could be handled with a unique constraint:
alter table dtr add constraint unq_dtr_userId_timeOut
unique (userId, timeOut);
Unfortunately (for this case), MySQL allows duplicate NULL values for unique constraints. So, you can do one of two things:
Use a default value, such as '2099-12-31' for time out.
Use a trigger to enforce uniqueness
In either case, the database itself will be validating the data, so you can be confident of data integrity regardless of how the data is inserted or updated.
I did it from my mobile not tested but you will get the idea of what is going on
if(isset($check))
{
$sql="SELECT * FROM dtr WHERE userID = $userID";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);
if(isset($check))
{
echo "Already in";
if(isset($check['timeIN']) && !isset($check['timeOUT']))
{
$sql = "UPDATE dtr SET timeOUT= now() WHERE userID=$userID";
mysqli_query($con, $sql);
mysqli_close($con);
}
}
else
{
$sql = "INSERT INTO dtr (userID,timeIN) VALUES ('$userID', now())";
mysqli_query($con, $sql);
mysqli_close($con);
echo 'Time IN Successful!';
}
}
else
{
echo 'Invalid USER ID. Please try again!';
mysqli_close($con);
}
i'm creating a form to insert data to logement table and lit table and also table espace.
i'm trying to insert data in all this tables that are connected like in the image
enter image description here
but i'm getting this error :
Warning: mysql_insert_id() expects parameter 1 to be resource, object given in F:\-- SOFTWARE\WEB-SERVER\esyphp\ep0002\data\localweb\school\buckup\BU-Projet\0008\ajoutez.php on line 88
ERROR: Could not able to execute INSERT INTO logement(Titre, AdresseLogement, Prix, NombrePerson, idTypeLogement) VALUES ('hgfrte','125669 hgfer','1236','33',''). Cannot add or update a child row: a foreign key constraint fails (`yandexd`.`logement`, CONSTRAINT `FK_Logement_idTypeLogement` FOREIGN KEY (`idTypeLogement`) REFERENCES `typedelogement` (`idTypeLogement`)) ERROR: Could not able to execute INSERT INTO lit(idLit, TypeDeLit) VALUES ('','kanape, canape'). Cannot add or update a child row: a foreign key constraint fails (`yandexd`.`lit`, CONSTRAINT `FK_Lit_idLogement` FOREIGN KEY (`idLogement`) REFERENCES `logement` (`idLogement`))
my php code is
if(isset($_POST['Submit'])){
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = #mysqli_connect("localhost", "root", "", "yandexd");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
switch ($_POST['logm-type']) {
case "Maison":
$_POST['logm-type'] = 1;
break;
case "Appartement":
$_POST['logm-type'] = 2;
break;
case "Chambre_privée":
$_POST['logm-type'] = 3;
break;
case "Chambre_partagée":
$_POST['logm-type'] = 4;
break;
}
$sql = "INSERT INTO logement(Titre, AdresseLogement, Prix, NombrePerson, idTypeLogement)
VALUES ('".$_POST['logm-titre']."','".$_POST['logm-adresse']."','".$_POST['logm-prix']."','".$_POST['logm-personne']."','".$_POST['logm-type']."')";
$thelogm_id = mysql_insert_id( $link );
$sql1 = "INSERT INTO espace(TypeDEspace, idLogement)
VALUES ('".$_POST['logm-espace']."','".$thelogm_id."')";
$sql2 = "INSERT INTO lit(TypeDeLit, idLogement)
VALUES ('".$_POST['logm-typelit']."','".$thelogm_id."')";
if(mysqli_query($link, $sql)){
echo "Le logement est ajouté.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
if(mysqli_query($link, $sql1)){
echo "Le logement est ajouté.";
} else{
echo "ERROR: Could not able to execute $sql1. " . mysqli_error($link);
}
if(mysqli_query($link, $sql2)){
echo "Le logement est ajouté.";
} else{
echo "ERROR: Could not able to execute $sql2. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}
else {
I tried all solution found on stackoverflow, but i can't solve the problem
If the client sends you a string in logm-type that doesn't exactly match one of the four you've mentioned in your switch statement, your code will pass the string they gave you as if it was the ID, in which case the error message you're seeing is the best case scenario.
Your code is using POST values in SQL queries directly, which is not a good idea - what if the client (accidentally or deliberately) includes an apostrophe?
now i changed the code to
$sql = "INSERT INTO logement(Titre, AdresseLogement, Prix, NombrePerson, idTypeLogement)
VALUES ('".$_POST['logm-titre']."','".$_POST['logm-adresse']."','".$_POST['logm-prix']."','".$_POST['logm-personne']."','".$_POST['logm-type']."')";
$thelogm_id = mysql_insert_id( $link );
$sql1 = "INSERT INTO espace(TypeDEspace, idLogement)
VALUES ('".$_POST['logm-espace']."','".$thelogm_id."')";
$sql2 = "INSERT INTO lit(TypeDeLit, idLogement)
VALUES ('".$_POST['logm-typelit']."','".$thelogm_id."')";
but i did received this error
Warning: mysql_insert_id() expects parameter 1 to be resource, object given in F:-- SOFTWARE\WEB-SERVER\esyphp\ep0002\data\localweb\school\buckup\BU-Projet\0008\ajoutez.php on line 87
Le logement est ajouté.Le logement est ajouté.ERROR: Could not able to execute INSERT INTO lit(TypeDeLit, idLogement) VALUES ('sofa, canape, lit',''). Cannot add or update a child row: a foreign key constraint fails (yandexd.lit, CONSTRAINT FK_Lit_idLogement FOREIGN KEY (idLogement) REFERENCES logement (idLogement))
Your calling mysql_insert_id out of sequence.
It returns the generated ID from the last successful query, which means you have to execute $sql first.
Try this:
// this declares the sql query, but hasn't executed it.
$sql = "INSERT INTO logement(Titre, AdresseLogement, Prix, NombrePerson, idTypeLogement)
VALUES ('".$_POST['logm-titre']."','".$_POST['logm-adresse']."','".$_POST['logm-prix']."','".$_POST['logm-personne']."','".$_POST['logm-type']."')";
// this executes the sql. Now mysql_insert_id can fetch the id.
if(mysql_query($link, $sql)){
echo "Le logement est ajouté.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// call mysql_insert_id after executing $sql, otherwise you'll just get null
$thelogm_id = mysql_insert_id( $link );
if( is_null($thelogm_id)){
echo "ERROR: no id".
}
$sql1 = "INSERT INTO espace(TypeDEspace, idLogement)
VALUES ('".$_POST['logm-espace']."','".$thelogm_id."')";
$sql2 = "INSERT INTO lit(TypeDeLit, idLogement)
VALUES ('".$_POST['logm-typelit']."','".$thelogm_id."')";
if(mysqli_query($link, $sql1)){
echo "Le logement est ajouté.";
} else{
echo "ERROR: Could not able to execute $sql1. " . mysqli_error($link);
}
Be aware, if the query for $sql fails you'll not want to execute $sql1 and $sql2.
I am having a bit of trouble with referential integrity errors on my database final exam project. I have tried to figure it out myself, but to no avail, and I am hoping someone here can point me in the right direction.
The problem is that I have three tables with the first two being parent tables to the third table. I am trying to construct a php script that will update the two parent tables and then insert the data into the child table. What I have thus far, I thought would work, but whenever I try to use it, I get the following error:
INSERT INTO Purchases (CustomerID, PurchaseOrderNo, PurchaseTotal, DateOfPurchase, SalesPersonID,SpecialOrder) VALUES ('10', '0000','100.00','0000-00-00','5555','N')
Cannot add or update a child row: a foreign key constraint fails ('xxxxxx'.'Purchases', CONSTRAINT 'Purchases_ibfk_1' FOREIGN KEY ('CustomerID') REFERENCES 'CustomerInfo'('CustomerID') ON DELETE CASCADE ON UPDATE CASCADE)'
Any thoughts where I have gone wrong?
########## FOREIGN KEY CHECK START ##########
$sql = "select count(*) as count from CustomerInfo where '$customerid' = CustomerID";
$result = mysqli_query($con,$sql)
or die('Error: ' . mysql_error());
$row = mysqli_fetch_assoc($result);
if ( $row['count']==0 ){
"INSERT INTO CustomerInfo ('CustomerID') VALUES ('$customerid');";
echo "<p>Customer ID Not Found. <br />New CustomerID Created.</p>";
}
$sql2 = "select count(*) as count from EmployeeInfo where '$salespersonid' = SalesPersonID;";
$result2 = mysqli_query($con,$sql)
or die('Error: ' . mysql_error());
$row2 = mysqli_fetch_assoc($result2);
if ( $row2['count']==0 ){
"INSERT INTO EmployeeInfo ('SalesPersonID')VALUES ('$salespersonid');";
echo "<p>Salesperson ID Not Found. <br />New Salesperson ID Created.</p>";
}
########## FOREIGN KEY CHECK END ##########
########## DATA ENTRY SQL STATEMENT START ##########
$sql3 = "INSERT INTO Purchases (CustomerID,
PurchaseOrderNo,
PurchaseTotal,
DateOfPurchase,
SalesPersonID,
SpecialOrder)
VALUES ('$customerid',
'$purchaseorderno',
'$purchasetotal',
'$dateofpurchase',
'$salespersonid',
'$specialorder')";
########### DATA ENTRY SQL STATEMENT END ##########
########## INPUT SUCCESS/FAILURE REPORTING#########
if (mysqli_query($con, $sql3)) {
echo "<P>Record Successfully Created</P><BR />";
} else {
echo "Error: " . $sql9. "<br>" . mysqli_error($con);
}
mysqli_close($con);
echo "<P>Connection Successfully Closed.</P>";
You aren't executing your insert queries for CustomerInfo or EmployeeInfo
$sql = "select count(*) as count from CustomerInfo where '$customerid' = CustomerID";
$result = mysqli_query($con,$sql)
or die('Error: ' . mysql_error());
$row = mysqli_fetch_assoc($result);
if ( $row['count']==0 ){
###THE NEXT LINE DOESN'T DO ANYTHING###
"INSERT INTO CustomerInfo ('CustomerID') VALUES ('$customerid');";
echo "<p>Customer ID Not Found. <br />New CustomerID Created.</p>";
}
Also you don't want to put single quotes around the column name in your insert statements so instead of:
INSERT INTO CustomerInfo ('CustomerID') VALUES ('$customerid')
you want:
INSERT INTO CustomerInfo (CustomerID) VALUES ('$customerid')
<?php
$con=mysqli_connect("localhost","usr","pwd","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT id, Name, email FROM users WHERE status='ACTIVE'");
while($row = mysqli_fetch_array($result)){
// echo $row['Name']. " - ". $row['email'];
// echo "<br />";
$userid = $row['id'];
$username = $row['Name'];
$email = $row['email'];
mysqli_query($con, "INSERT INTO other_user (user_id, username, email)
VALUES ($userid, $username, $email)");
}
mysqli_close($con);
?>
i have the above code i am trying to insert data from one table to another
The above code do not returning any error but it do not puts any data to second table "other_user"
There is an error in INSERT query - you have to enclose strings in quotes, like this:
"INSERT INTO other_user (user_id, username, email)
VALUES ($userid, '$username', '$email')"
A single query would be enough:
$result = mysqli_query($con, "INSERT INTO other_user (user_id, username, email)
SELECT id, Name, email FROM users WHERE status='ACTIVE'");
No need for an agonizing slow row by row insert.
PS: The original error was leaving out quotes around your values.
You should use mysqli prepared statement to insert data to table. Now you don't use quotes in your query (probably that's why data is not inserted into second table) and even if you were, it would be still vulnerable to SQL Injection
I think you should carefully check the table design of your new table.
Check if the column names and types are what you expect.
Also user_id in your new table may be an autoincrement index and than if doesn't have to be inserted.