[Solved] INSERT row from another table using php PDO


Ok, so the issues you had/have were:

  • $barCode = $GET['id']); should have been $barCode = $GET['id'];, and possibly even $_GET['id'];
  • Your SELECT query selects the same field twice (SELECT Brand, Description, >Price<, Size, >Price<)
  • You’re also inserting in the same field twice: INSERT INTO adstable (Brand, Description, >Price<, Size, >Price<
  • You’re vulnerable to injection attacks, still

So let’s address the issues:

$barCode = isset($_GET['id']) ? $_GET['id'] : null;//avoids undefined index notice

Next, to use the same field twice in the SELECT query, you can define an alias, but you just don’t need the same field twice…

SELET SELECT Brand, Description, Price as price_1, Size, Price as price_2, Barcode FROM

Then, to protect against first degree injection attacks, let’s use a prepared statement instead of calling PDO::query with a GET parameter:

$stmt = $pdo->prepare('INSERT INTO adstable (Brand, Description, Price, Size, Barcode) 
      SELECT Brand, Description, Price, Size, Barcode FROM invtable 
      WHERE Barcode=:barcode'
);
$stmt->execute([':barcode' => $barCode]);

The code, then should look something like this:

$barCode = isset($_GET['id']) ? (int) $_GET['id'] : null;
// check $barCode is valid value, if not, don't bother connecting
if ($barCode) {
    $pdo = new PDO(
        sprintf(
            'mysql:host=%s;dbname=%s;charset=utf8', // add charset here!
            $host,
            $dbName
        ),
        $user, $password,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ]
    );
    $stmt = $pdo->prepare(
        'INSERT INTO adstable(Brand, Description, Price, Size, Barcode)
         SELECT Brand, Description, Price, Size, Barcode FROM invtable
         WHERE Barcode = :barcode'
    );
    $stmt->execute(
        [
            ':barcode' => $barCode
        ]
    );
}

That should do the trick. But seriously: error messages tell you what’s wrong Read them

3

solved INSERT row from another table using php PDO