How to update an array using PHP - php

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.

Related

PHP prepared statement doesn't work with intval()

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.

Fatal error after tried to fix update statement

I tried to make the update statement to be safety againts sql injection but its give me this erro Fatal error: Call to a member function bind_param() on a non-object on line 39
$pid = $_POST['pid'];
$pagetitle = $_POST['pagetitle'];
$linklabel = $_POST['linklabel'];
$keyword = $_POST['keyword'];
$descriere = $_POST['descriere'];
$data = $_POST['data'];
$pagebody = $_POST['pagebody'];
// Filter Function -------------------------------------------------------------------
function filterFunction ($var) {
$var = nl2br(htmlspecialchars($var));
$var = str_replace("/", "\\\\", $var);
$var = preg_replace("~/~", "\\\\", $var);
return $var;
}
$pagetitle = filterFunction($pagetitle);
$linklabel = filterFunction($linklabel);
$keyword = filterFunction($keyword);
$descriere = filterFunction($descriere);
$data = filterFunction($data);
$pagebody = filterFunction($pagebody);
// End Filter Function --------------------------------------------------------------
include_once "../conx.php";
// Add the updated info into the database table
$stmt = $con->prepare("UPDATE pages SET (pagetitle, linklabel, keywords, description, pagebody, lastmodified) VALUES (?, ?, ?, ?, ?, ?) WHERE id = ?");
// TODO check that $stmt creation succeeded
// "s" means the database expects a string
$stmt->bind_param("sssssss", $pagetitle, $linklabel, $keyword, $descriere, $pagebody, $data, $pid);
$stmt->execute();
$stmt->close();
line 39 is $stmt->bind_param("sssssss", $pagetitle, $linklabel, $keyword, $descriere, $pagebody, $data, $pid);
it is necessary to make this or i can revert to how it was before
$query = mysqli_query($con, "UPDATE pages SET pagetitle='$pagetitle', linklabel='$linklabel', pagebody='$pagebody', lastmodified='now()' WHERE id='$pid'") or die (mysqli_error($con));
Didn't this produce an error?
$con->prepare("UPDATE pages SET (pagetitle, linklabel, keywords, description, pagebody, lastmodified) VALUES (?, ?, ?, ?, ?, ?) WHERE id = ?");
this should be
$con->prepare("UPDATE pages SET pagetitle=?, linklabel=?, keywords=?, description=?, pagebody=?, lastmodified=? WHERE id = ?");
Refer: http://dev.mysql.com/doc/refman/5.7/en/update.html
now you can proceed to bind parameters
$stmt->bind_param("sssssss", $pagetitle, $linklabel, $keyword, $descriere, $pagebody, $data, $pid);

Function won't select data from database

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;
}
}

Mysqli INSERT command followed by an UPDATE

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();

php mysql prepared statements issue

I'm starting with mysql prepared statements and I can't advance due to an error that I don't understand. Here's my function to update de db:
public function updateUserData($user_label,$user_alliance, $score, $rank, $timestamp, $user_id, $db_object){
$sql='UPDATE users SET label = ?, alliance = ?, points = ?, position = ?, modified = ?, WHERE user_id = ?';
$label = $user_label;
$alliance = $user_alliance;
$points = $score;
$position = $rank;
$modified = $timestamp;
$user_id_q = $user_id;
$stmt = $db_object->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $db_object->error, E_USER_ERROR);
}
$stmt->bind_param('ssiiii',$label,$alliance,$points,$position,$modified,$user_id_q);
/* Execute statement */
$stmt->execute();
echo $stmt->affected_rows;
$stmt->close();
}
Here's how I use it:
//Get user Data
$user = new user();
$page_clasif = $user->getPagClasif($ch,$url_clasif);
$user_label = $user->findPlayerName($page_clasif);
$user_alliance = $user->findAllianceName($page_clasif);
$rank = $user->findRank($page_clasif);
$score = $user->findScore($page_clasif);
$user_id = $user->findPlayerId($page_clasif);
$version = $user->findVersion($page_clasif);
$user_universe = $user->findUniverse($page_clasif);
//Get install date as timestamp
$core = new core();
$timestamp = $core->dateAsTimestamp();
//Update User
$user->updateUserData($user_label,$user_alliance,$score,$rank,$timestamp,$user_id,$conn);
Here's the error:
PHP Fatal error: Wrong SQL: UPDATE users SET label = ?, alliance = ?, points = ?, position = ?, modified = ?, WHERE user_id = ? Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE user_id = ?'
Any ideas?
Thanks in advance.
You have a superfluous comma before the WHERE keyword:
$sql='UPDATE users SET label = ?, alliance = ?, points = ?, position = ?, modified = ?, WHERE user_id = ?';
// remove this comma --^

Categories