1

How can I submit a table row data to another table using an input field in PHP and MYSQL?

HTML

<form method="post" action="post.php">
  <input type="number" name="code" placeholder="Code..."/>
  <input type="submit" name="submit" value="Submit"/>
</form>

Post.php

if (isset($_POST['submit'])) {
    $code = $_POST['code'];


    $getCode = "SELECT * FROM products WHERE code=$code";
    mysqli_query($connection, $getCode);
    if ($_POST['code'] == $code) {
      $migrating = "INSERT INTO managment(price) VALUES ($price) SELECT 
      price FROM products";
      mysqli_query($connection, $migrating);
      header("location: index.php");
    }
}

What is wrong with my code?

James Z
  • 12,209
  • 10
  • 24
  • 44
Hamza Ali
  • 25
  • 5

1 Answers1

0

The syntax is :

INSERT INTO managment(price) SELECT price FROM products

Maybe you want add a WHERE clause :

INSERT INTO managment(price) SELECT price FROM products WHERE code=$code

Note: in your code, $_POST['code'] == $code doesn't make sense, because of $code = $_POST['code'] earlier.

I also suggest you to have a look to How can I prevent SQL injection in PHP? to secure your queries.


Your code updated (untested) :

if (isset($_POST['submit'])) {
    $code = $_POST['code'];

    $getCode = "SELECT * FROM products WHERE code=$code";
    $result = mysqli_query($connection, $getCode);
    if (!$result) die("Error: " . mysqli_error($connection));
    $row = mysqli_fetch_assoc($result);
    if ($row['code'] == $code) {
        $migrating = "INSERT INTO managment(price) 
                      SELECT price FROM products WHERE code=$code";
        $result2 = mysqli_query($connection, $migrating);
        if (!$result2) die("Error: " . mysqli_error($connection));
        header("Location: index.php");
        exit;
    }
}
Syscall
  • 19,327
  • 10
  • 37
  • 52