Update multiple row using PHP and MySQL - php

I'm new to php and mySql. I'm trying to update multiple row by using php and mysql.
I'm having problem with updating multiple row in MySQL database. It's only update the last row of the table in the database. For example, user click on view product. The page will list 10 product that currently in the database. And user wants to update product information by on-click method. After finishing update, user click submit.
The problem is it only capture and update information of the last product in the table. I tried to put it in the foreach() function. But it doesnt work.
Please help. I just learned PHP and mySQL less than a week. I very much appreciate any helps.
<?php
include 'dbconn.inc.php';
include 'functions.inc.php';
$sql = "SELECT * FROM products";
$res = $mysqli->query($sql);
while( $row = $res->fetch_array(MYSQLI_ASSOC) ){
$products($row['id']) = 'id';
}
$id = $mysqli->real_escape_string( $_POST['id'] );
$weight = $mysqli->real_escape_string( $_POST['weight'] );
$name = $mysqli->real_escape_string( $_POST['name'] );
$supplier_id = $mysqli->real_escape_string( $_POST['supplier_id'] );
$price = $mysqli->real_escape_string( $_POST['price'] );
$description = $mysqli->real_escape_string( $_POST['description'] );
foreach( $products as $id){
$sql = "UPDATE products
SET
`id` = '$id',
`weight` = '$weight',
`price` = '$price',
`name` = '$name',
`supplier_id` = '$supplier_id',
`description` = '$description'
WHERE `id` = '$id'";
}

A couple of issues:
First, you're declaring the variable $id twice.
You should be using the $key not the $value in the loop
Instead, try this:
foreach( $products as $key => $value){
$sql = "UPDATE products
SET
`id` = '$id',
`weight` = '$weight',
`price` = '$price',
`name` = '$name',
`supplier_id` = '$supplier_id',
`description` = '$description'
WHERE `id` = '$key'";
}
The reason for using the array key rather than its value is because in the below line you are setting the key of the array to the values returned from the first query:
while( $row = $res->fetch_array(MYSQLI_ASSOC) ){
$products($row['id']) = 'id';
}
I might suggest instead doing this:
$products = array();
while( $row = $res->fetch_array(MYSQLI_ASSOC) ){
$products[]['id'] = $id;
}
foreach( $products as $product){
$sql = "UPDATE products
SET
`id` = '$id',
`weight` = '$weight',
`price` = '$price',
`name` = '$name',
`supplier_id` = '$supplier_id',
`description` = '$description'
WHERE `id` = '" . $product['id'] . "'";
}

Related

SQL: Edit only if input is not null

I currently working on simple Christmas gifts database :) and I have a problem with my Edit function. When user select existing gift for edit (by ID) and enter new values (for example for price) I want only that the price is changed and everything else is kept as it was. I try to use function IFNULL but my code is not working as I expected. Everytime i get new value for price, the other fields are erased.
My code (Iam using MySQL):
else if($_REQUEST['btn_submit']=="Edit")
{
$gifts_id = $_POST["gifts_id"];
$year = $_POST["year"];
$whom = $_POST["whom"];
$category = $_POST["category"];
$what = $_POST["what"];
$shop = $_POST["shop"];
$url = $_POST["url"];
$price = $_POST["price"];
$note = $_POST["note"];
$status = $_POST["status"];
Db::query("
UPDATE `gifts`
SET
`year` = ifnull('$year',`year`),
`whom` = ifnull('$whom',`whom`),
`category` = ifnull('$category',`category`),
`what` = ifnull('$what',`what`),
`shop` = ifnull('$shop',`shop`),
`url` = ifnull('$url',`url`),
`price` = ifnull('$price',`price`),
`note` = ifnull('$note',`note`),
`status` = ifnull('$status',`status`)
WHERE
`gifts_id` = '$gifts_id';
");
echo("<p>Gift with ID:'$gifts_id' successfully updated</p>");
}
Thanks for answers!
PS: I code just for fun so please be mercyful :)
If your want to properly edit your values, first you should fill all your inputs with your old values so the user can edit them or leave them as it was. Then you can check that all the values are not null before calling the sql as shown below:
else if($_REQUEST['btn_submit']=="Edit")
{
$gifts_id = $_POST["gifts_id"];
$year = $_POST["year"];
$whom = $_POST["whom"];
$category = $_POST["category"];
$what = $_POST["what"];
$shop = $_POST["shop"];
$url = $_POST["url"];
$price = $_POST["price"];
$note = $_POST["note"];
$status = $_POST["status"];
if(!empty($gifts_id)&&!empty($year)&&!empty($whom)&&!empty($category)&&!empty( $what)&&!empty($shop)&&!empty($url )&&!empty($price)&&!empty($note)&&!empty($status))
{
Db::query("
UPDATE `gifts`
SET
`year` = ifnull('$year',`year`),
`whom` = ifnull('$whom',`whom`),
`category` = ifnull('$category',`category`),
`what` = ifnull('$what',`what`),
`shop` = ifnull('$shop',`shop`),
`url` = ifnull('$url',`url`),
`price` = ifnull('$price',`price`),
`note` = ifnull('$note',`note`),
`status` = ifnull('$status',`status`)
WHERE
`gifts_id` = '$gifts_id';
");
echo("<p>Gift with ID:'$gifts_id' successfully updated</p>");
}
else
{
echo("<p>Gift with ID:'$gifts_id' was not updated, please check your data</p>");
}
IFNULL tests only for the special NULL value, and quoted strings are never null. You should compare the strings with ''.
Db::query("
UPDATE `gifts`
SET
`year` = if('$year' = '',`year`, '$year'),
`whom` = if('$whom' = '',`whom`, '$whom'),
...
WHERE
`gifts_id` = '$gifts_id';
");
Another option is to build the query dynamically.
$assign_array = array();
foreach (array('year', 'whom', 'category', ...) AS $field) {
if ($_POST[$field] !== '') {
$assign_array[] = "`$field` = '{$_POST[$field]}'";
}
}
$assign_string = implode(',', $assign_array);
Db::query("
UPDATE `gifts`
SET $assign_string
WHERE `gifts_id` = '$gifts_id';");
Note, however, that this is vulnerable to SQL injection. If your DB API allows you to create prepared queries and provide an array of values, you should do that. You can build up the parametrized query and array of values in a similar manner to this.

ON DUPLICATE KEY insertS new record instead of updating with Unique key

I have a issue, my INSERT ... ON DUPLICATE KEY UPDATE is inserting a new record instead of updating the row, the Table i am using has both an primary key and a unique key. So i am confused to why this is happening.
Table
CREATE TABLE `Product` (
`Product_Id` bigint(255) NOT NULL AUTO_INCREMENT,
`Resturant_ID` bigint(255) NOT NULL,
`Product_Desc` text NOT NULL,
`Product_Name` varchar(100) NOT NULL,
`Product_Price` decimal(8,0) NOT NULL,
`Add_On_ID` int(11) NOT NULL,
PRIMARY KEY (`Product_Id`),
UNIQUE KEY `Product_Name` (`Product_Name`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8
QUERY
$add_product_errors = array();
if (isset($_POST['add'])) {
$item_name = $_POST['item_name'];
$desc = $_POST['desc'];
$price = $_POST['price'];
$rest_id = mysqli_real_escape_string($dbc, $_SESSION['Resturant_ID']);
if (empty($_POST['price']) || !filter_var($_POST['price'], FILTER_VALIDATE_FLOAT) || ($_POST['price'] <= 0)) {
$add_product_errors['price'] = "Please enter a product price";
}
if (empty($_POST['item_name'])) {
$add_product_errors['item_name'] = "Please enter a name";
}
if (empty($_POST['desc'])) {
$add_product_errors['desc'] = "Please enter a product description";
}
$query = "INSERT INTO Product(Resturant_ID,Product_Name,Product_Desc,Product_Price) VALUES (?,?,?,?)
ON DUPLICATE KEY
UPDATE
Resturant_ID = VALUES(Resturant_ID)
,Product_Name = VALUES(Product_Name)
,Product_Desc = VALUES(Product_Desc)
,Product_Price = VALUES(Product_Price)";
$run_query = mysqli_prepare($dbc, $query);
if (!$run_query) {
die(mysqli_error($dbc));
}
mysqli_stmt_bind_param($run_query, 'sssd', $rest_id, $item_name, $desc, $price);
$execute = mysqli_stmt_execute($run_query);
$item_name = strip_tags($_POST['item_name']);
$desc = strip_tags($_POST['desc']);
//100 - changes the way the decimal displays in database
$price = strip_tags($_POST['price'] * 100);
if ($execute) {
echo "<script> alert('Addrrss Saved')</script>";
} else {
echo "<b>Oops! we have an issue </b>";
mysqli_stmt_close($run_query);
}
}
?>
The syntax just looks off to me. Maybe try writing the SQL and testing it first in console or MySQL workbench or whatever first? Try this:
$query = "INSERT INTO Product(Resturant_ID,Product_Name,Product_Desc,Product_Price) VALUES (?,?,?,?)
ON DUPLICATE KEY UPDATE
Resturant_ID = ?
,Product_Name = ?
,Product_Desc = ?
,Product_Price = ?";
$run_query = mysqli_prepare($dbc, $query);
if (!$run_query) {
die(mysqli_error($dbc));
}
mysqli_stmt_bind_param($run_query, 'issdissd', $rest_id, $item_name, $desc, $price, $rest_id, $item_name, $desc, $price);
Or maybe ? eight times and binding things twice... not sure off hand if mysqli supports named parameters...
Updated [again] per Martin's feedback.

Check to Insert or Update table

See the code below, it check if the data exist in the table, if not exist then insert it or else update the table.
As you can see it look a bit messy - is there anyway to improve the code logic or something smaller? I have a few tables that need doing same thing.
foreach ($sheet as $data) {
// Get Phone ID
$dataPhoneID = mysql_escape_string($data['handset']['phone_id']);
if (isset($stocks[$dataPhoneID])) {
$stockPhone = $stocks[$dataPhoneID ];
$phoneName = mysql_escape_string($stockPhone['description']);
$stock = mysql_escape_string($stockPhone['stock']);
$SQL = "SELECT * FROM phone_affiliate WHERE affiliate_id = 1 AND affiliate_phone_id = '$dataPhoneID'";
$q = mysql_query($SQL);
if (mysql_num_rows($q) == 0) {
$SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')";
if (mysql_query($SQLInsert)) {
$phone_id = mysql_insert_id();
$SQLInsert = "INSERT INTO phone_affiliate (phone_id, affiliate_id, affiliate_phone_id, stock) ";
$SQLInsert .= "VALUE('$phone_id', '1', '$dataPhoneID', '$stock')";
mysql_query($SQLInsert) or die(mysql_error());
}
} else {
$row = mysql_fetch_assoc($q);
$phone_id = $row['phone_id'];
$SQLUpdate = "UPDATE phone_affiliate set stock = '$stock' WHERE affiliate_id = 1 AND phone_id = $phone_id";
mysql_query($SQLUpdate) or die(mysql_error());
}
// Similar code block above for other tables.
}
}
Note: I am aware about PDO but I don't have time to replace it on existing system.
Use mysql's REPLACE INTO or INSERT... ON DUPLICATE KEY UPDATE. For example:
foreach ($sheet as $data) {
// Get Phone ID
$dataPhoneID = mysql_escape_string($data['handset']['phone_id']);
if (isset($stocks[$dataPhoneID])) {
$stockPhone = $stocks[$dataPhoneID ];
$phoneName = mysql_escape_string($stockPhone['description']);
$stock = mysql_escape_string($stockPhone['stock']);
$SQLInsert = "INSERT INTO phone_affiliate (affiliate_id, affiliate_phone_id, stock) ";
$SQLInsert .= "VALUES ('1', '$dataPhoneID', '$stock') ";
$SQLInsert .= "ON DUPLICATE KEY UPDATE stock = '$stock'";
mysql_query($SQLInsert);
if (mysql_insert_id()) {
$SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')";
mysql_query($SQLInsert);
$phone_id = mysql_insert_id();
$SQLUpdate = "UPDATE phone_affiliate set phone_id = $phone_id WHERE affiliate_id = 1 AND affiliate_phone_id = $dataPhoneID_id";
}
}
}
Also you can use INSERT IGNORE construction

Product ID is not being stored in the database

can anyone help? my code doesn't seem to store the value of product id here in my code have a look I am also getting the ID from another table
<?php
include("Connection.php");
$dTime = time();
$myValue = $_REQUEST['dValue'];
echo "<p>
The time is: {$dTime}<br/>
The choice is {$myValue}
</p>
";
$sql = "Select ID from product where NAME = '$myValue'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
$pid=$row["PRODUCT_ID"];
$sql2 = "INSERT INTO `starbucks`.`order_details` (
`ID` ,
`ORDER_ID` ,
`PRODUCT_ID` ,
`QTY`
)
VALUES (
NULL , '', '$pid', '1'
)";
$result2 = mysql_query($sql2);
?>
updated the code
$id = $row["ID"]
instead of:
$id = $row;
You have an incorrect array value for $id instead of the array's ID key:
$id = $row;
// Should be
$id = $row['ID'];
in your original code there is no error handling,you should do something like this:
$sql = "Select ID from product where NAME = '$myValue'";
if ($sql) {
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
$pid = $row["PRODUCT_ID"];
$sql2 = "INSERT INTO `starbucks`.`order_details` (
`ID` ,
`ORDER_ID` ,
`PRODUCT_ID` ,
`QTY`
)
VALUES (
NULL , '', '$pid', '1'
)";
$result2 = mysql_query($sql2);
if (!$result2) {
echo mysql_error();
break;
}
} else {
echo mysql_error();
}
And see what error you get.

Data is not being stored in the database

My code is getting the ID from another, after I get that ID I will insert it to another table. The thing is it's not working, any idea why?
<?php
session_start();
include("Connection.php");
if (isset($_POST['submit'])){
$name = $_POST['customerName'];
mysql_query("INSERT INTO `starbucks`.`orders` (
`ID` ,
`NAME` ,
`TOTAL_PRICE` ,
`TOTAL_ITEMS` ,
`TIME`
)
VALUES (
'' , '$name', '', '',NOW())");
$_SESSION['user'] = $name;
}
$dTime = time();
$myValue = isset($_REQUEST['dValue']) ?$_REQUEST['dValue'] : '';
echo "The time is: {$dTime}<br/>
The choice is {$myValue} ";
$sql = "Select * from product where NAME = '{$myValue}'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)){
$price = $row['PRICE'];
$id = $row['ID'];
echo $id;
$sql2 ="INSERT INTO starbucks`.order_details (ID, ORDER_ID, PRODUCT_ID, QTY) VALUES ('', '', '$id', '1')";
$result2 = mysql_query($sql2);
}
?>
extra back tick in the INSERT, either add another or remove

Categories