I would like to have data inserted in one table, and data updated in another through prepared statements in mysqli. Trying the following only executes the INSERT command:
EDITED:
if($stmt=$mysqli->prepare("SELECT bids_id, bid, fruit_volume FROM basket ORDER BY bid DESC")) {
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($bids_id, $bid, $fruit_volume);
while($stmt->fetch()) {
$stack = array($bids_id, $bid, $fruit_volume);
array_push($all_fruits, $stack);
}
$stmt->free_result();
}
foreach ($all_fruits as $fruits) {
if ($_POST["offer"] == $fruits[1] && $volume < $fruits[2]) {
$stmt2 = $mysqli->prepare("INSERT INTO oranges (username, price, volume, date) VALUES (?, ?, ?, ?)");
$stmt2->bind_param('sdis', $user, $price, $volume, $today);
$stmt2->execute();
$stmt3 = $mysqli->prepare("UPDATE basket SET fruit_volume = ? WHERE bids_id = ?");
$stmt3->bind_param('ii', 800, 1);
$stmt3->execute();
}
}
$mysqli->close();
bind_param passes by reference not by value,so you need to have those values in variables before they can be referenced
$a=800;
$b=1;
foreach ($all_fruits as $fruits) {
if ($_POST["offer"] == $fruits[1] && $volume < $fruits[2]) {
$stmt2 = $mysqli->prepare("INSERT INTO oranges (username, price, volume, date) VALUES (?, ?, ?, ?)");
$stmt2->bind_param('sdis', $user, $price, $volume, $today);
$stmt2->execute();
$stmt3 = $mysqli->prepare("UPDATE basket SET fruit_volume = ? WHERE bids_id = ?");
$stmt3->bind_param('ii',$a, $b);
$stmt3->execute();
}
}
Try this instead
foreach ($all_fruits as $fruits) {
if ($_POST["offer"] == $fruits[1] && $volume < $fruits[2]) {
$stmt2 = $mysqli->prepare("INSERT INTO oranges (username, price, volume, date) VALUES (?, ?, ?, ?)");
$stmt2->bind_param('sdis', $user, $price, $volume, $today);
$stmt2->execute();
$stmt3 = $mysqli->prepare("UPDATE basket SET fruit_volume = ? WHERE bids_id = ?");
$stmt3->bind_param('ii', 800, 1);
$stmt3->execute();
}
}
$mysqli->close();
Related
I have an app that is written using procedural PHP. I've created an insert page where I take a buck of addresses and pass them as an array and insert them in the database. There I have the id of the row and then an orderId, the address type, and the address. Now I want to be able to update a specific one. Until now I've come up with the following:
// update new supplier order
function updateSupplierOrder($conn, $orderDate, $datePickup, $dateDelivery, $timePickup, $timeDelivery, $car, $carType, $goodsDescription, $paletChange, $paletNo, $supplier, $orderObservation, $paymentDate, $value, $addressPickup, $addressDelivery, $userid, $orderID) {
$sql1 = "UPDATE suppliersOrders SET supplierId = ?, date = ?, datePickup = ?, timePickup = ?, goodsDescription = ?, dateDelivery = ?, timeDelivery = ?, carType = ?, carNo = ?, paletChange = ?, paletNo = ?, value = ?, invoice = ?, observations = ?, operator = ? WHERE id = ?;";
$stmt1 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt1, $sql1)) {
header ("location: ../suppliersOrders?error=failedupdateorder");
exit();
}
mysqli_stmt_bind_param($stmt1, "isssssssisisssii", $supplier, $orderDate, $datePickup, $timePickup, $goodsDescription, $dateDelivery, $timeDelivery, $carType, $car, $paletChange, $paletNo, $value, $paymentDate, $orderObservation, $userid, $orderID);
mysqli_stmt_execute($stmt1);
mysqli_stmt_close($stmt1);
for ($i=0; $i<count($addressPickup); $i++) {
$address = $addressPickup[$i];
$type = '1';
$sql2 = "UPDATE suppliersOrdersAddress SET address = ?, operator = ? WHERE orderId = ? AND addressType = ?;";
$stmt2 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt2, $sql2)) {
header ("location: ../suppliersOrders?error=failedupdateaddress");
exit();
}
mysqli_stmt_bind_param($stmt2, "siii", $address, $userid, $orderID, $type);
mysqli_stmt_execute($stmt2);
mysqli_stmt_close($stmt2);
}
for ($i=0; $i<count($addressDelivery); $i++) {
$address = $addressDelivery[$i];
$type = '2';
$sql2 = "UPDATE suppliersOrdersAddress SET address = ?, operator = ? WHERE orderId = ? AND addressType = ?;";
$stmt2 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt2, $sql2)) {
header ("location: ../suppliersOrders?error=failedupdateaddress");
exit();
}
mysqli_stmt_bind_param($stmt2, "siii", $address, $userid, $orderID, $type);
mysqli_stmt_execute($stmt2);
mysqli_stmt_close($stmt2);
}
header("location: ../suppliersOrders-edit.php?id=$orderID");
}
But this will update all the addresses of an order and a type. How can I update based on the id from the table, this will make sure that the right address is updated.
Help would be appreciated.
I found a solution to the issues. The simplest way to be able to update the row that I needed was to add the id value from the row in an array and do the update based on the WHERE clause that had the id value. This way I was able to update just the needed value/row.
After executing INSERT statement there is no single error thrown and my database table is empty ,someone help please!
Service file for calling INSERT statement
roomservice.php
<?php
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
if(isset($_POST['hotelName']) && isset($_POST['hasTV']) &&
isset($_POST['beds']) && isset($_POST['price'])){
$roomName = $_POST['hotelName'];
$hasTV = $_POST['hasTV'];
$beds = $_POST['beds'];
$price = $_POST['price'];
echo addRoom($roomName,$hasTV,$beds,$price);
}
function addRoom($hotelName, $hasTV, $beds , $price){
global $conn;
$rarray = array();
$stmt = $conn->prepare("INSERT INTO rooms (hotelname, hastv, beds, price) VALUES (?, ?, ?, ?)");
$stmt->bind_param("sss", $hotelName, $hasTV, $beds , $price);
if($stmt->execute()){
$rarray['sucess'] = "okej";
}else{
$rarray['error'] = "Database connection error";
}
return json_encode($rarray);
}
?>
Angular component file where i call the service file with data passed through form.
addroom.component.ts
public addRoom() {
const body = new HttpParams()
.set('hotelname', this.roomForm.value.hotelName)
.set('hastv', this.roomForm.value.hasTV)
.set('beds', this.roomForm.value.beds)
.set('price', this.roomForm.value.price);
console.log(body.toString());
this._api.post('roomservice.php', body.toString()).subscribe((data: any) => {
console.log(data);
// localStorage.setItem('token', JSON.parse(data['_body']).token);
this._router.navigate(['./']);
}, (error) => {
const obj = JSON.parse(error['_body']).error;
const element = <HTMLElement> document.getElementsByClassName('alert')[0];
element.style.display = 'block';
element.innerHTML = obj.split('\\r\\n').join('<br/>').split('\"').join('');
});
}
}
rooms table
client response
You're trying to pass 4 arguments to the bind function but you have entered only 3 parameters. That's why its not working.
The solution is to change these two lines:
$stmt = $conn->prepare("INSERT INTO rooms (hotelname, hastv, beds, price) VALUES (?, ?, ?, ?)");
$stmt->bind_param("sss", $hotelName, $hasTV, $beds , $price);
to:
$stmt = $conn->prepare("INSERT INTO `rooms` (`hotelname`, `hastv`, `beds`, `price`) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $hotelName, $hasTV, $beds , $price);
Please look my code:
$insertStmt = $conn->prepare("INSERT INTO orders (OrderID, OrderTrackingNumber, OrderTotal, CustomerID) VALUES (?, ?, ?, ?)");
$insertStmt->bind_param("ssdi", $orderID, strval("Not Ship Yet"), $orderTotal, $userID);
if ($insertStmt->execute()) {
$insertStmt = $conn->prepare("INSERT INTO ordersproducts (OrderID, ProductID, ProductSold) VALUES (?, ?, ?)");
$updateStmt = $conn->prepare("UPDATE products SET ProductQuantity = ? WHERE ProductID = ?");
foreach ($orderedProducts as $orderedProduct) {
$productQuantity = intval($orderedProduct->ProductQuantity) - intval($orderedProduct->ProductAddedQuantity);
$insertStmt->bind_param("sii", $orderID, intval($orderedProduct->ProductID), intval($orderedProduct->ProductAddedQuantity));
$updateStmt->bind_param("ii", intval($productQuantity), settype($orderedProduct->ProductID, "integer"));
if ($insertStmt->execute() && $updateStmt->execute()) {
if ($updateStmt->affected_rows == 1) {
$isSuccefull = TRUE;
} else {
$isSuccefull = FALSE;
break;
}
} else {
$isSuccefull = FALSE;
echo $insertStmt->error . " | " . $updateStmt->error;
break;
}
}
}
At the line of $updateStmt->bind_param, if I convert $orderedProduct->ProductID to int by intval($orderedProduct->ProductID), the updateStmt will not work ($updateStmt->affected_rows = 0). However, I use settype($orderedProduct->ProductID, "integer"); then it will work like a champ. And only this place gets that issue; others work very well.
Why?
Thanks for helping me.
I'm working on a new website at the moment and I have a bit of a problem.
I look if an item exist, if it does, it will execute an insert query. The insert query works but the problem is that the select query doesn't work
Class
public function doubt($event_id)
{
$exist = $this->conn->prepare("SELECT * FROM agenda WHERE id=?");
$exist->bind_param('s', $event_id);
$exist->execute();
$exist->get_result();
if($exist->num_rows != null)
{
$now = new DateTime();
$date = $now->getTimestamp();
$status = 2;
$stmt = $this->conn->prepare("INSERT INTO absence (user_id,event_id,status,ip,date) VALUES (?, ?, ?, ?, ?) ");
$stmt->bind_param('sssss', $_SESSION['user_session'], $event_id, $status, $_SERVER['REMOTE_ADDR'], $date);
$stmt->execute();
$stmt->close();
return true;
}
else
{
return false;
}
}
Is it possible to have a MySQLi prepared statement within the fetch() call of a previous statement? If not, what's the best way around it?
Example code:
if($stmt = $link->prepare("SELECT item FROM data WHERE id = ?")) {
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($item);
while( $stmt->fetch() ) {
/* Other code here */
$itemSummary = $item + $magic;
if($stmt2 = $link->prepare("INSERT INTO summaries (itemID, summary) VALUES (?, ?)")) {
$stmt2->bind_param("is", $itemID, $itemSummary);
$stmt2->execute();
$stmt2->close();
}
}
}
This is the single connection way:
if($stmt = $link->prepare("SELECT item FROM data WHERE id = ?")) {
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->store_result(); // <-- this
$stmt->bind_result($item);
while( $stmt->fetch() ) {
/* Other code here */
$itemSummary = $item + $magic;
if($stmt2 = $link->prepare("INSERT INTO summaries (itemID, summary) VALUES (?, ?)")) {
$stmt2->bind_param("is", $itemID, $itemSummary);
$stmt2->execute();
$stmt2->store_result(); // <-- this
/*DO WHATEVER WITH STMT2*/
$stmt2->close();
}
}
}
You should be able to do that, although you make have to start a second connection.
Or use store_result.