error with a foreign key constraint fails - php

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.

Related

column doesnt match when its empty

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

Add Form Data and Get Data from Another Table to Form a New Record After Submit - Php MySQL

5 fields from Table 1 come from the Php Form. 5 fields are extracted from Table 2, Table 3, Table 4, and Table 5.
Is this doable from Php?
Tried both multiple INSERT SELECT and VIEWS; however, a novice compared to some.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("site", "user", "password", "database");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$new_record_id = trim($_GET["id"]);
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email, city, state) VALUES ('Peter', 'Parker', 'peterparker#mail.com', 'williamsburg', 'new york')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Attempt insert query1 execution
$sql1 = "INSERT INTO persons (SELECT cust_type, cust_revenues, cust_since FROM customer) VALUES ('Existing', '3029', '2016') WHERE id = $new_record_id";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Attempt insert query2 execution
$sql2 = "INSERT INTO persons (SELECT order_no, order_date FROM orders) VALUES ('293048', '11/26/2016') WHERE id = $new_record_id";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
When submitting the Form, a new record should get created with data in all 10 fields. Currently, not happening.
I think I will replace the code with PDO hardened PHP statements and MySQLi. As well since no error codes are given (it returns a clean page), I think the result set is too big. I replaced the query to only perform an INSERT from the Form. The other tables will be aggregated into Views.

Conditional insert or update in mysql

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.

how to update value of the specific column from a table after deleting data

guy's i need help for this problem guy's
i have a table with 4 column. no, name, address, phone. the case is after i do deleting one data i must decrease column no with how many data i delete.
last time i make a program using vb.net i can do this. i use this code i can do it well
Dim ab As Integer
ab = lvrak.Items(i).SubItems(4).Text
Dim stok As New SqlClient.SqlCommand("Update tbl_barangluar set jumlah_barang=jumlah_barang - '" & ab & "' where kode_barang='" & _
lvrak.Items(i).SubItems(0).Text & "'")
stok.Connection = koneksi
stok.ExecuteNonQuery()
but now i need to do that in php function. and im really dont know how to do it.
i try just do ex. update temp5 set no='$no' - 1 and it not going well. someone please help me
This my Trial PHP
<?php
include("../../Connections/koneksi.php");
$no= $_POST['no_check'];
// Attempt insert query execution
$sql = "DELETE FROM temp5 WHERE no='$no'";
if(mysqli_query($db, $sql)){
echo "Records were deleted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
// Close connection
mysqli_close($db);
?>
<?php
include("../../Connections/koneksi.php");
$no= $_POST['no_check'];
// Attempt insert query execution
$sql = "alter table temp5 auto_increment = 1";
if(mysqli_query($db, $sql)){
echo "Records were deleted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
// Close connection
mysqli_close($db);
?>
<?php
include("../../Connections/koneksi.php");
$no= $_POST['no_check'];
$min = 1;
// Attempt insert query execution
$sql = "UPDATE temp5 SET no=no -1 where no";
if(mysqli_query($db, $sql)){
echo "Records inserted successfully.";
} else{
echo "Records inserted failed ";
}
mysqli_close($db);
?>
I will add a picture before and after delete function has do.
the problem is there. i have try to do limiting them but is give more eror.
in the 1st picture is contain all the data before delete. and i will do delete the data with no 4. and the result is in picture 2. that result is wrong.. the result must be 1,2,3,4
You need to update the count after delete success
UPDATE temp5 SET no=no -1
PHP :
<?php include("../../Connections/koneksi.php");
$no= $_POST['no_check'];
$sql = "DELETE FROM temp5 WHERE no='$no'";
if(mysqli_query($db, $sql)){
$sql1 = "UPDATE temp5 SET no=no -1";
mysqli_query($db, $sql1);
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}

insert into select on duplicate key update

I'm try to create a database where i save users search.
I want insert term when this term don't exist and adding +1 when exist but all other specific field on database are the same.
Example:
user1 search playstation with price 1 = insert into database
user2 search playstation with price 1 = +1 on the same row generated by user1
user3 search playstation with price 1 and condition new = insert into database a new record
I have write this but don't work:
<?php
$link = mysqli_connect("localhost", "root", "root", "keyword");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// attempt insert query execution
$sql = "INSERT INTO keyword (id, search, category, mn, mx, site, itmcond, free, sortorder, type, payp) VALUES ('".$_GET["id"]."', '".$_GET["search"]."', '".$_GET["category"]."', '".$_GET["mn"]."', '".$_GET["mx"]."', '".$_GET["site"]."', '".$_GET["itmcond"]."', '".$_GET["free"]."', '".$_GET["sortorder"]."', '".$_GET["type"]."', '".$_GET["payp"]."')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Anyone can help me to understand where use INSERT INTO for add search to database, SELECT for find the term previously insered and ON DUPLICATE KEY UPDATE for adding +1 for the same search.
Thanks!
$sql = "INSERT INTO keyword (id, search, category, mn, mx, site, itmcond, free, sortorder, type, payp) VALUES ('".$_GET["id"]."', '".$_GET["search"]."', '".$_GET["category"]."', '".$_GET["mn"]."', '".$_GET["mx"]."', '".$_GET["site"]."', '".$_GET["itmcond"]."', '".$_GET["free"]."', '".$_GET["sortorder"]."', '".$_GET["type"]."', '".$_GET["payp"]."')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
//add this
die();
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>

Categories