How can I change from INSERT INTO to UPDATE - php

(Sorry for my English writing)
This is my coding for insert data
$insertChecklist = 'INSERT INTO checklists(`ADMIN_ID`, `COMPUTER_ID`) VALUES(?, ?);';
$stmtChecklist = $connection->prepare($insertChecklist);
$stmtChecklist->bind_param('ii', $_POST['ADMIN_ID'], $_POST['COMPUTER_ID']);
$isInsert = $stmtChecklist->execute();
$lastInsertId = mysqli_insert_id($connection);
$stmtChecklist->close();
$insertInstalledProgram = 'INSERT INTO checklist_programs(`CHECKLIST_ID`, `PROGRAM_ID`) VALUES(?, ?);';
$stmtProgramId = $connection->prepare($insertInstalledProgram);
$stmtProgramId->bind_param('ii', $lastInsertId, $programId);
foreach ($_POST['PROGRAM_ID'] as $program)
{
$programId = $program;
$stmtProgramId->execute();
}
$stmtProgramId->close();
$connection->close();
if ($isInsert) {
// echo($lastInsertId);
header('Location: OverViewCheckList.php');
exit(0);
}
And I need to change this Insert into to Update
I don't know how. Please help :(
Thank you.

It is not clear what you really want
maybe something like that:
$updateChecklist = 'UPDATE checklists SET `ADMIN_ID` = ?, `COMPUTER_ID` = ? WHERE id = ?';
$stmtChecklist = $connection->prepare($insertChecklist);
$stmtChecklist->bind_param('iii', $_POST['ADMIN_ID'], $_POST['COMPUTER_ID'], $_POST['ID']);
$res = $stmtChecklist->execute();

Related

How to update an array using 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.

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.

PDO update statement problems

I am converting from mysqli to PDO and very much a beginner with this. Here is my update statement for my database 'users'
public function pdo_update_test() {
$sql = "UPDATE users SET visible_password = ?, hashed_password = ?, ";
$sql .="temp_hashed_password = ?, email = ?, first_name= ?, last_name = ?, ";
$sql .="position = ?, location = ?, city = ?, country = ?, institution = ? ";
$sql .="interests = ?, profile_comment = ? WHERE id =" . $this->id;
$query = $handler->prepare($sql);
$result = array($visible_password, $hashed_password, $temp_hashed_password, $email,
$first_name, $last_name, $position, $location, $city, $country, $institution,
$interests, $profile_comment);
$query->execute($result);
if (($query = $handler->prepare($sql)) === false) {
print_r($handler->errorInfo());
}
if ($query->execute($result) === false) {
print_r($query->errorInfo());
}
}
I am using ? rather than nameholders because once I have this working I am going to try to make it abstract so I can use it in all the classes in my site and I have found it easier with ? than nameholders. When I run the following it fails to work. I am sure an obvious error on my part but I can't seem to see the issue....
$user = new User();
$user->id= 256;
$visible_password = "Bob";
$user->pdo_update_test();
I have found a solution to make the whole thing dynamic. I won't presume that its going to be helpful for others (as I am the beginner) but i though I would post it anyway....
If you see problems or have criticisms please let me know
public function pdo_update_test(){
$attributes = $this->attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
if(isset($value))
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id=". $this->id;
$query = $handler->prepare($sql);
$query->execute(array());
}
What you need is to create SET statement for the query dynamically. To make it contain only actual fields you have values for.
So, for the code given, it should produce a query
UPDATE users SET visible_password = ? WHERE id = ?
-- but not one you wrote above with all the fields listed
and it is not PDO related problem - it's rather just basic string manipulation, every PHP user is supposed to be able to write. If you can't, you can refer to PDO tag wiki for the code to adopt.
To make it work your code have to be like this
$user = new User();
$user->id= 256;
$data = array('visible_password' => "Bob");
$user->pdo_update_test($data);
where pdo_update_test will create the above SQL query out of $data array

Mysqli Prepared Statement Troubleshooting

I'm stumped, I recently had this working in plain Mysqli statements, but was told to avoid injection to write it using prepared statements. The truncate is the only thing that seems to work. Any advice?
$con=mysqli_connect(localhost,"username","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = 'twitch'
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json?channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert->bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = twitch
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json? channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert = bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();
mysqli_close($con);
There is no function bind_param(), it is a method of mysqli_stmt
You use it like so:
$insert->bind_param()
Check here for more information on mysqli_stmt

Array into MYSQL

I've a few examples but nothing that I can grasp. I have the below code, the echos work but the insert does not. I believe I'm suppose to explode these? Not sure but maybe someone can give me a hint with my own example.
$con=mysqli_connect(localhost,"username","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = 'twitch'
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json?channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert = bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = twitch
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json? channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert = bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();
mysqli_close($con);
You're missing quotes around your string values:
"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ($username[0], $viewer[0])"
should be
"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ('$username[0]', '$viewer[0]')"
You would spot this error easily if you add error handling to your code. Look into using mysqli_error().
$result = mysqli_query($con,"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ('$username[0]', '$viewer[0]')");
if (!result) {
// This should be done better than this
echo mysqli_error();
exit;
}
Since I can't tell from your code what the source of $data[0]->channel_count is I will also mention that you should at least escape your insert variables with mysqli_real_escape_string(). Even better, use prepared statements.

Categories