I am trying to execute the following query using a PDO Prepared Statement, but when I call $query->fetch();
it throws an exception SQLSTATE[HY000]: General
You would be correct in that PDO (and I believe any PHP method?) does not allow for multiple queries in a single by default. There are some workarounds which you can read about more, such as:
PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)
but they do increase the risk of SQL injection so it is ill-advised.
Run your first query which is the insert then after success on that one get the last insertid then use the id on your next query.. Eg.
<?php
try {
$db = new Database(); //Create a new object of type Database establishing a connection to the MySQL database
$query = $db->prepare("INSERT INTO orders (order_type`, `item`, `amount`, `price`, `price_btc`, `status`, `timestamp`, `placed_by`, `secret`, `first_name`, `last_name`, `address_1`, `address_2`, `city`, `zip_code`, `country`, `state`, `phone_number`) VALUES(:order_type, :item, :amount, :price, :price_btc, :status, :timestamp, :placed_by, :secret, :first_name, :last_name, :address_1, :address_2, :city, :zip_code, :country, :state, :phone_number)");
$query->execute(array( /* your values*/ ));
$lastId = $db->lastInsertId(); // fetch last insert id, after success.
$order = $db->prepare("SELECT * FROM `orders` WHERE `ID`=?");
$order->bindValue(1, $lastId);
$order->execute();
//Fetch your records and display.
}
catch (PDOException $e) {
echo "Error : " . $e->getMessage();
}
?>
I left some part of the codes like you did, but the important thing is to run the insert first then collect the last
So just run your queries one by one
$db = new Database(); //Create a new object of type Database establishing a connection to the MySQL database
$query = $db->pdo->prepare("INSERT INTO `orders` (`order_type`, `item`, `amount`, `price`, `price_btc`, `status`, `timestamp`, `placed_by`, `secret`, `first_name`, `last_name`, `address_1`, `address_2`, `city`, `zip_code`, `country`, `state`, `phone_number`)
VALUES(:order_type, :item, :amount, :price, :price_btc, :status, :timestamp, :placed_by, :secret, :first_name, :last_name, :address_1, :address_2, :city, :zip_code, :country, :state, :phone_number)"
); //Prepare the first query
/*HERE IS SOME CODE TO BIND PLACEHOLDERS TO SOME VALUES*/
$query->execute();
$order = $db->pdo->query("SELECT * FROM `orders` WHERE `ID`=LAST_INSERT_ID()")->fetch(PDO::FETCH_ASSOC);