1

can it be combine into 1 query?

this is the query that im trying to combine? or is there a better way to relate these to table?

$insert_row = $mysqli->query("INSERT INTO orderlist 
(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)
VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')");

$insert_row1 = $mysqli->query("INSERT INTO order 
(BuyerName,BuyerEmail,TransactionID)
VALUES ('$buyerName','$buyerEmail','$transactionID')");

when i run these both only one query is functional, so what im trying to do is to make them both works.

im open to any suggestion

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Mohd Fadli
  • 143
  • 10

2 Answers2

1

The reason why your second query isn't working is because of the use of order and not escaping it; it is a MySQL reserved word:

Sidenote: ORDER is used when performing a SELECT... ORDER BY...

Checking for errors would have shown you the syntax error such as:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax near 'order

Therefore, wrap it in ticks:

$insert_row1 = $mysqli->query("INSERT INTO `order` ...

or rename your table to something other than a reserved word, say orders for example.

If you wish to combine both queries, you can use multi_query()

Example from the manual:

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";

if (!$mysqli->multi_query($sql)) {
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

do {
    if ($res = $mysqli->store_result()) {
        var_dump($res->fetch_all(MYSQLI_ASSOC));
        $res->free();
    }
} while ($mysqli->more_results() && $mysqli->next_result());
?>

I also need to point out that your present code may be open to SQL injection since I do not know if you are escaping your data.

If not, then use prepared statements, or PDO with prepared statements, they're much safer.

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
0

try to add IF statement.

if ($insert_row = $mysqli->query("INSERT INTO orderlist(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')"));
{
$insert_row1 = $mysqli->query("INSERT INTO order (BuyerName,BuyerEmail,TransactionID) VALUES ('$buyerName','$buyerEmail','$transactionID')");
}
kim de castro
  • 299
  • 6
  • 19