Doubt with php and mysql

0

Can someone help me get a doubt here? I'm starting in php now, I created a database in mysql (phpmyadimin) and listed the primary key of one table as a foreign key in another. At the time I run the php script with the idea of saving in the database does not save, but if I remove the relationship between the tables, save. What can this be?

Follow the code

$sql = mysqli_query("INSERT INTO usuario(nome) VALUES('$nome')");
$sql = mysqli_query("INSERT INTO imc(peso,altura,imc) VALUES('$peso','$altura','$imc')");

Below table structure.

'Estrutura da tabela 'imc'
--

CREATE TABLE IF NOT EXISTS 'imc' (
  'id' int(11) NOT NULL AUTO_INCREMENT,
  'peso' varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  'altura' varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  'imc' varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  'id_usuario' int(11) NOT NULL,
  PRIMARY KEY ('id'),
  KEY 'id_usuario' ('id_usuario')
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=4 ;

Estrutura da tabela 'usuario'
--

CREATE TABLE IF NOT EXISTS 'usuario' (
  'id' int(11) NOT NULL AUTO_INCREMENT,
  'nome' varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY ('id')
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=4 ;

--
-- Extraindo dados da tabela 'usuario'
--

INSERT INTO 'usuario' ('id', 'nome') VALUES
(1, 'shs'),
(2, 'sem nome'),
(3, 'ertt');

--
-- Constraints for dumped tables
--

--
-- Limitadores para a tabela 'imc'
--
ALTER TABLE 'imc'
  ADD CONSTRAINT 'relacionamento' FOREIGN KEY ('id_usuario') REFERENCES 'usuario' ('id');
    
asked by anonymous 07.01.2016 / 21:11

1 answer

1

ID of foreign keys are relationships, they are not an automatic data entry so that the relationship is maintained. You have to maintain the integrity of the relationship when you enter the data.

You must first get the user ID when you save data in the user table, and then use that ID to save the data in the table imc.

Example:

$sql = mysqli_query("INSERT INTO usuario(nome) VALUES('$nome')");
$last_id = mysqli_insert_id();
$sql = mysqli_query("INSERT INTO imc(usuario_id, peso,altura,imc) VALUES($last_id, '$peso','$altura','$imc')");
    
07.01.2016 / 21:34