php


Php Mysql insert with multiple foreign keys


I'm trying to do an insert where there are FK in a table but it's not working..
My db name is bd_telefonos
my db looks like this:
table marcas:
idmarcas --> PK AI
nombre
table sistemas_operativos:
idsistemas_operativos -->PK AI
nombre
table telefonos:
modelo
idtelefonos --> PK AI
resolucion_alto
resolucion_ancho
peso
bateria
marcas_idmarcas --> FK
sistemas_operativos_idsistemas_operativos -- > FK
My php looks like this:
<?php
include_once('conexion/conexion.php');
$con = new conectar();
$modelo= $_POST['modelo'];
$alto= $_POST['alto'];
$ancho= $_POST['ancho'];
$peso= $_POST['peso'];
$bateria= $_POST['bateria'];
$nombresis = $_POST['nombresis'];
$nombremarca = $_POST['nombremarca'];
$sSql = "INSERT INTO `bd_telefonos`.`telefonos` (`modelo`, `resolucion_alto`, `resolucion_ancho`, `peso`, `bateria`) VALUES ('$modelo', '$alto', '$ancho', '$peso', '$bateria')";
if(!mysqli_query($con->conectarse(), $sSql)){
$resp = 'error ';
}
else{
/*=============================================================================
= select recently insert =
=============================================================================*/
$sSqlId = "SELECT MAX(id) as `id` FROM `bd_telefonos`.`telefonos`";
if($respuesta = mysqli_query($con->conectarse(), $sSqlId)){
foreach ($respuesta as $resp) {
$id = $resp['id'];
}
}
/*========================================================
= Insert sistemas_operativos
========================================================*/
$sSqlMas = "INSERT INTO `bd_telefonos`.`sistemas_operativos` (`idsistemas_operativos`, `nombre`) VALUES ('$id', '$nombresis')";
if (mysqli_query($con->conectarse(), $sSqlMas)) {
$resp = 'success';
echo $resp;
} else {
$resp = 'error';
echo $resp;
}
/*========================================================
= Insert marcas
========================================================*/
$sSqlMass = "INSERT INTO `bd_telefonos`.`marcas` (`idmarcas`, `nombre`) VALUES ('$id', '$nombremarca')";
if (mysqli_query($con->conectarse(), $sSqlMass)) {
$resp = 'success';
$resp = 'error';
echo $resp;
}
}
mysqli_close($con->conectarse());
?>
it's not working, it's just not making insert in my table telefonos , what am i doing wrong?
help please :(
Use $conn->insert_id rather than MAX(ID).
$conn = new mysqli("hostname", "db_user_name", "db_password", "db_name");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$modelo= $_POST['modelo'];
$alto= $_POST['alto'];
$ancho= $_POST['ancho'];
$peso= $_POST['peso'];
$bateria= $_POST['bateria'];
$nombresis = $_POST['nombresis'];
$nombremarca = $_POST['nombremarca'];
$sSql = "INSERT INTO `telefonos` (`modelo`, `resolucion_alto`, `resolucion_ancho`, `peso`, `bateria`) VALUES ('$modelo', '$alto', '$ancho', '$peso', '$bateria')";
if ($conn->query($sSql) === TRUE) {
$id = $conn->insert_id;
/*========================================================
= Insert sistemas_operativos
========================================================*/
$sSqlMas = "INSERT INTO `sistemas_operativos` (`idsistemas_operativos`, `nombre`) VALUES ('$id', '$nombresis')";
if ($conn->query($sSqlMas) === TRUE) {
echo 'success';
$sistemas_operativos_id = $conn->insert_id;
} else {
echo "Error: " . $sSqlMas . "<br>" . $conn->error;
}
/*========================================================
= Insert marcas
========================================================*/
$sSqlMass = "INSERT INTO `marcas` (`idmarcas`, `nombre`) VALUES ('$id', '$nombremarca')";
if ($conn->query($sSqlMass) === TRUE) {
echo 'success';
$marcas_id = $conn->insert_id;
} else {
echo "Error: " . $sSqlMass . "<br>" . $conn->error;
}
/************** Update FK ***************/
$update_sql = "UPDATE telefonos SET marcas_idmarcas ='$marcas_id', sistemas_operativos_idsistemas_operativos ='$sistemas_operativos_id' WHERE idtelefonos = '$id'";
if ($conn->query($update_sql) === TRUE) {
echo 'Successfully Update';
} else {
echo "Error: " . $update_sql. "<br>" . $conn->error;
}
} else {
echo "Error: " . $sSql . "<br>" . $conn->error;
}
$conn->close();
Do you want to update the below two column in telefonos table
marcas_idmarcas --> FK
sistemas_operativos_idsistemas_operativos -- > FK
you can get last insert value from both the tables and update in telefonos table

Related Links

CreateSignedURL failure AWS SSE-C with PHP
Setup sending post request from android to php script
Getting the value between two points on a curve
PHP Move_uploaded_file not moving my file to directory
PayPal IPN does not fire when users cancel PreApproval Apdaptive Payments
What does the this code in socket.io mean
Codeigniter : How to show logged In User Name in every methods (or view page) without repeating same code in every function
Wordpress Multisite - User roles
Stream 360 Video from Youtube in Unity - Get Direct Link from API
Facbook SDK 5 and graph api 2.x get my photos
I want to count dish names at specific dates
Laravel 5 input validation with name regular expression
How to save updated lists in database using jquery or ajax in php
General idea on how to create a multiplatform application
Updating database structure to nested sets (baum) - family tree
How to display excel file data in the web page exactly as it is in the file in phpexcel?

Categories

HOME
jboss
powerbi
cucumber
clearcase
adfs3.0
applescript
kivy
filesize
hdfs
websocket
angular-meteor
cocotb
gtk
yahoo
tiff
documentum
cuba-platform
webstore
complexity-theory
distributed-computing
sonicwall
rest-assured
cocos2d-android
maven-plugin
boomi
nullreferenceexception
cmake-gui
jest
jitsi
gollum-wiki
mod-wsgi
nurbs
tracing
background-color
clipboard
sap-lumira
oracleforms
amazon-cloudtrail
fatfs
commonsware-cwac
xcrun
express-session
love2d
ms-solver-foundation
nanogallery
praat
resampling
dagger
morphline
apache-toree
vesta
jenkins-slave
qvtkwidget
swift2.3
cyanogenmod
libreoffice-writer
ol3-google-maps
skip-lists
mura
freshdesk
nslayoutconstraint
word-2007
deedle
kendo-treeview
oid
researchkit
nvda
gnucash
simian
sharepoint-apps
utf-16
boost-proto
linuxbrew
nette
dnx50
apple
sequence-sql
unidata
clarion
scala-macros
scala-swing
sql-processor
fasterxml
jquery-mobile-flipswitch
webmethod
roxy-fileman
spring-social-linkedin
jmenubar
unrealscript
jquery-transit
virtual-channel
objective-c-runtime
eager-loading
gprof
struts2-json-plugin
word-frequency
prefuse
dropshadow
wcf-callbacks
delphi-prism
directshow.net
active-record-query
ninject-interception
uninstaller
raw-data
iphone-sdk-4.3
self-tracking-entities
spring-modules
source-code-protection
fuzzy-comparison
gui-designer

Resources

Encrypt Message