1

I am trying to run an insert query using PHP. As mentioned in the title it works in phpmyadmin but does not work in php code.

Below is the code:

if ($result) {

  session_start();
  $_SESSION['fname'] = $firstname;
  $firstname_sess = $_SESSION['fname'];
  $sql_uid = " SELECT id FROM users WHERE firstname = '" . $firstname_sess . "' ";
  var_dump($sql_uid);
  $sql_uid_result = mysqli_query($db, $sql_uid);
  $sql_uid_array = mysqli_fetch_array($sql_uid_result, MYSQLI_ASSOC);
  $sql_uid_final = $sql_uid_array['id'];
  var_dump($sql_uid_final);
  mysqli_query('SET foreign_key_checks = 0');
  $uo_uid = "INSERT INTO `user_order` (user_id) VALUES ('$sql_uid_final')";
  var_dump($uo_uid);
  $uo_uid_final = mysqli_query($db, $uo_uid);
  var_dump($uo_uid_final);
  if ($uo_uid_final) {

    echo "All good";
  } else {
    echo "Something went wrong 1";
  }
  //header('Location: productsform.php');

} else {
  echo "Somethingwentwrong2";
}

Code Explanation:

  1. There are two tables users and user_order
  2. Trying to fetch existing user's user id from users table to user_order table.
  3. user_order table has user_id as a foreign key referencing id(PK) field in users table.
  4. Facing issue while inserting the value in user_order table.

Although the code works through PHP myadmin or terminal but is not working via PHP code.

I have gone through the similar links given below: 1. mysql DELETE works on phpmyadmin but not on php script 2. SQL query working in phpmyadmin but not in php 3. mysqli_query works in phpmyadmin but not in php 4. Query works in phpMyAdmin but not in php

And many more but could not find anything. Any help would really be appreciated.

Thank you in advance.

Isaac Bennetch
  • 11,830
  • 2
  • 32
  • 43

1 Answers1

1

One problem I see in your code is this line:

mysqli_query('SET foreign_key_checks = 0');

You haven't provided $db as the first argument of mysqli_query.

If that's not the issue, could you provide the mylsqli_error() for the query that fails?

Michael Beeson
  • 2,840
  • 2
  • 17
  • 25
  • Hi @Michael Beeson $db as the first argument, worked. Thank you for the quick support. Also when I tried mysqli_error() below was the error description: Error description: Cannot add or update a child row: a foreign key constraint fails (`cafepoc`.`user_order`, CONSTRAINT `user_order_ibfk_1` FOREIGN KEY (`id`) REFERENCES `users` (`id`)) which clearly mentions there has been something wrong with the foreign_key_check mysqli_query. Once again thank you for the response. – Shatakshi Agnihotri May 20 '18 at 16:16
  • Glad it helped! Accept the answer to give me that juicy kudos! – Michael Beeson May 20 '18 at 16:17