简体   繁体   中英

INSERT INTO is not working foreign key php

The check 'if' works but the values are not updating into the database. what is wrong?
I think is the code is right, it confirms the sucess from the insert. The foreign key is emp_id that references the primary key from a table called empresa (idempresa).

    // get post from other file
      @$pegar = $_POST['postempresa'];
      $q = " SELECT idempresa FROM empresa WHERE idempresa = $pegar " ;


      if (isset($_POST['submit'])) {
        // Connect to the database
        $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);




        // Grab the medida data from the POST


        $fk_empresa = mysqli_real_escape_string($dbc, trim($_POST['chaveestrangeira']));


        $prato = mysqli_real_escape_string($dbc, trim($_POST['f_prato']));
        $medida = mysqli_real_escape_string($dbc, trim($_POST['f_medida']));
        $preco = mysqli_real_escape_string($dbc, trim($_POST['f_preco']));
        $pessoas = mysqli_real_escape_string($dbc, trim($_POST['f_pessoas']));
        $categoria = mysqli_real_escape_string($dbc, trim($_POST['f_categoria']));
        $obs = mysqli_real_escape_string($dbc, trim($_POST['f_obs']));
        $foto = mysqli_real_escape_string($dbc, trim($_FILES['f_foto']['name']));
        $foto_type = $_FILES['f_foto']['type'];
        $foto_size = $_FILES['f_foto']['size']; 




        if (!empty($prato) && !empty($medida) && !empty($preco) && !empty($pessoas) && !empty($categoria) ) {

          if ((($foto_type == 'image/gif') || ($foto_type == 'image/jpeg') || ($foto_type == 'image/pjpeg') || ($foto_type == 'image/png')) && ($foto_size > 0) && ($foto_size <= GW_MAXSIZECARD)) {
            if ($_FILES['f_foto']['error'] == 0) {
              // Move the file to the target upload folder
              $target = GW_UPCARD . $foto;
              if (move_uploaded_file($_FILES['f_foto']['tmp_name'], $target)) {
                // Write the data to the database


                $query = 

                "INSERT INTO cardapio SET

                 emp_id = '$q',
                 prato = '$prato',
                 medida = '$medida',
                 preco = '$preco',
                 pessoas = '$pessoas',
                 categoria = '$categoria',
                 obs = '$obs',
                 foto = '$foto'


                 ";

                mysqli_query($dbc, $query);

                echo mysql_error();

                // Confirm success with the user
                echo '<p>Cardapio enviado!</p>';
                echo '<p><strong>ID EMPRESA</strong> ' . $fk_empresa . '<br />';
                echo '<p><strong>prato:</strong> ' . $prato . '<br />';
                echo '<strong>Medida:</strong> ' . $medida . '<br />';
                echo '<strong>Preço:</strong> ' . $preco . '<br />';
                echo '<strong>Categoria:</strong> ' . $categoria . '<br />';
                echo '<strong>Obs:</strong> ' . $obs . '<br />';
                echo '<img src="' . GW_UPCARD . $foto . '" alt="Score image" /></p>';
                echo '<p><a href="index.php">Voltar para admin</a></p>';

                // Clear the medida data to clear the form
                $prato = "";
                $medida = ""; 
                $preco = "";
                $pessoas = "";
                $categoria = "";
                $obs = "";
                $foto = "";



                mysqli_close($dbc);

              }
              else {
                echo '<p class="error">Tivemos um erro no upload da imagem.</p>';
              }
            }
          }
          else {
            echo '<p class="error">A imagem precisa ter extensão GIF, JPEG, ou PNG e menor que ' . (GW_MAXSIZECARD / 1024) . ' KB.</p>';
          }

          // Try to delete the temporary screen shot image file
          @unlink($_FILES['foto']['tmp_name']);
        }
        else {
          echo '<p class="error">Por favor, preencha todos os campos.</p>';
        }
      }
    ?>

Two things.

You are not executing query. Execute it like this

$rec    = " SELECT idempresa FROM empresa WHERE idempresa = $pegar " ;
$result =   mysqli_query($rec);
if($result){
    $row    =   myqsli_fetch_assoc($result);
    $q      =   $row['idempresa'];
}else{
    $q = '';
}

now the other thing is that your insert query is totally wrong. it does not use set keyword . Use it like this

$query = "INSERT INTO cardapio 
            (emp_id ,prato ,medida ,preco , pessoas , categoria , obs ,foto )
            VALUES
            ('$q','$prato','$medida','$preco','$pessoas','$pessoas','$categoria','$obs','$foto')";
mysqli_query($query);

CREATE TABLE IF NOT EXISTS empresa ( idempresa int(10) unsigned NOT NULL AUTO_INCREMENT, nomefantasia varchar(255) NOT NULL, razaosocial varchar(255) NOT NULL, cnpj varchar(12) NOT NULL, cepemp varchar(8) NOT NULL, estadoemp varchar(2) NOT NULL, empcidade varchar(255) CHARACTER SET utf8 NOT NULL, ruaemp varchar(255) NOT NULL, bairroemp varchar(255) NOT NULL, numeroemp varchar(255) NOT NULL, compemp varchar(20) NOT NULL, categoriaemp varchar(45) NOT NULL, logomarca varchar(64) NOT NULL, telefoneum varchar(20) NOT NULL, telefonedois varchar(20) NOT NULL, emailum varchar(255) NOT NULL, emaildois varchar(255) NOT NULL, PRIMARY KEY ( idempresa ) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

-- ALTER TABLE cardapio ADD CONSTRAINT cardapio_ibfk_3 FOREIGN KEY ( emp_id ) REFERENCES empresa ( idempresa ) ON DELETE CASCADE ON UPDATE CASCADE;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM