How to UPDATE all rows in SQL with one query? - php

I have an existing DATABASE of Prestashop, and I have made small modifications to it. I made a separate PHP page which gets data from table with products (only the data i need) and shows me all products that ARE IN THAT TABLE, one after another. I also have a function which updates a products, on which i press EDIT.
So, in a simple words i can update a single product per click. But now I have about 220 products, and in order to update a value (price) for each product, now, i must click EDIT for each product, 220 times.
Is there a way to make a query in order to update all rows after i click a BUTTON?
Bellow I will show you some basic parts from my script:
GET function:
<?php
$strSQL = "SELECT * FROM ps_product";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
while($objResult = mysql_fetch_array($objQuery))
{
?>
<!-- HTML CODE -->
<? } ?>
UPDATE function for each product
if($_POST["hdnCmd"] == "Update")
{
$strSQL = "UPDATE ps_product_shop SET ";
$strSQL .="id_product = '".$_POST["txtEditid_product"]."' ";
$strSQL .=",price = '".$_POST["txtEditprice"]."' ";
$strSQL .=",active = '".$_POST["txtEditactive"]."' ";
$strSQL .="WHERE id_product = '".$_POST["hdnEditid_product"]."' ";
$objQuery = mysql_query($strSQL);
if(!$objQuery)
{
echo "Error Update [".mysql_error()."]";
}
}
$_POST["hdnEditid_product] is the product id value that is taken from table.
Please help me to understand how to make a similar **UPDATE function** **which will update all rows (product_id) at once?
As an example i must work around this code:
if($_POST["UPDATEALLPRODUCTS"] == "Update")
{
$strSQL = "UPDATE ps_product_shop SET ";
$strSQL .=",price = '".$_POST["txtEditprice"]."' ";
$strSQL .="WHERE id_product = '".$_POST["hdnEditid_product"]."' ";
$objQuery = mysql_query($strSQL);
if(!$objQuery)
{
echo "Error Update [".mysql_error()."]";
}
}
but what I must add/change here:
$strSQL .="WHERE id_product = '".$_POST["hdnEditid_product"]."' ";

To update all rows to the same value run this query
UPDATE ps_product_shop SET price='".$_POST["txtEditprice"]."';
NOTE: Every records in ps_products_shop will get the same value in price.

How about this ?
Make an array like this : id => price, and then :
$prices = array(
1=>300,
5=>180,
...
);
foreach ($prices as $id => $price) {
$query = "UPDATE ps_product_shop SET price='".$price."' WHERE
id_product='".$id."' ";
mysql_query($query);
}

One way to do it, if you insist on using a single query:
<?php
$product_updates = array("1" => "500", "2" => "1299.99");
$sql_query = "UPDATE my_database.products SET price = CASE id ";
foreach ($product_updates as $key => $value) {
$sql_query .= "WHEN '$key' THEN '$value' ";
}
$sql_query .= "END;";
mysql_query($sql_query);
?>

I am assuming that the page already has the updated price / info that you need and therefore it is just plucking the php variables out
UPDATE ps_product_shop SET price
= CASE
WHEN id_product= $id_product_1
THEN '$edited_price_1'
WHEN id_product = $id_product_2
THEN '$edited_price_2'
Without seeing the form structure it is hard to see what would be the correct variable names but hopefully you can take the code and go with it, i have to do something similar and have PhP autobuild the query using this method

Related

How to insert stock quantity and update into another table?

I'm trying to update the quantity of stock when a new stock is added. I'm using array because I want to add more than one product in the page. But the data is not insert into the db and no update on the quantity of stock too. What do I miss on this code?
<?php
include 'db_connection.php';
if(isset($_POST["submit4"])){
foreach($_POST['fk_product'] as $index => $searchid){
$sql="INSERT INTO supplier (supplier_name, date_in, fk_product, quantity_in) VALUES ('".$_POST['supplier_name']."','".$_POST['date_in']."','".$_POST['fk_product'][$index]."', '".$_POST["quantity_in"][$index]."')";
$quantity_bal=$_POST['quantity_bal'];
if($quantity_bal==0){
$sql="UPDATE product set quantity_bal= quantity_ori + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}else if($quantity_bal!=0){
$sql="UPDATE product set quantity_bal= quantity_bal + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}
$query = mysqli_multi_query($conn,$sql);
if($query){
header("location:product.php");
}
}
}
?>
What you're missing is that you need to concatenate the queries, with the use of = assignment operator, you've just overridden the former string, so it should be like this
foreach($_POST['fk_product'] as $index => $searchid){
$sql = "INSERT INTO supplier (supplier_name, date_in, fk_product, quantity_in) VALUES ('".$_POST['supplier_name']."','".$_POST['date_in']."','".$_POST['fk_product'][$index]."', '".$_POST["quantity_in"][$index]."')";
$quantity_bal = $_POST['quantity_bal'];
if($quantity_bal == 0){
//I'm presuming that the quantity_ori is a variable here 'coz you're trying to sum up with the original to the latest one
$sql .= "UPDATE product set quantity_bal= $quantity_ori + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}else if($quantity_bal != 0){
$sql .= "UPDATE product set quantity_bal= $quantity_bal + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}
}
We changed the = symbol in your update queries into .= and then your quantity_ori earlier doesn't have the $ symbol, since we're presuming it's a variable, don't forget the $

Getting only first entry php mysql

I have an mysqli table having values as such:-
id | price
65| 7000
67| 7001
And a php code to echo both out using an array variable:-
require('setup.php'); // got connection
$array = array(0 => 65, 1 => 67);
$d = implode("," , $array);
$sql = "SELECT price FROM trade WHERE id IN('$d')";
$query = mysqli_query($conn, $sql);
if($query){
while ($row = mysqli_fetch_array($query)) {
echo $row['price'].'<br>';
}
}
else {
echo mysqli_error($conn);
}
The output should come as
7000
7001
but it's only 7000.
You need to do IN(65,67) while you are doing IN('65,67')
So remove ' around $d
Code needs to be:-
$sql = "SELECT price FROM trade WHERE id IN($d)";
Note:- use fetch_assoc() for lighter array iteration (as it only gives associative array resultset)
while ($row = mysqli_fetch_assoc($query)) {
Working snippet :- http://rextester.com/FEFBWZ40805
Remove extra single quotes in IN() tag.
Corrected code:
$sql = "SELECT price FROM trade WHERE id IN($d)";
$sql Outputs:
SELECT price FROM trade WHERE id IN(65,67)
You can check the code here:
Edit your query as below,
$sql = "SELECT price FROM trade WHERE id IN($d)";
Hope this helps.
Passing $d withing quotes makes the IN('65,66') look like this during execution so you need to remove that as by the default convention you just need to pass an array. So change your query to:
SELECT price FROM trade WHERE id IN($d)
Please check your SQL query
$sql = "SELECT price FROM trade WHERE id IN('$d')";
Please change this query like below:
$sql = "SELECT price FROM trade WHERE id IN($d)";
You should not use single quote with php varible.
Try something like this:
require('setup.php');
$array = [65, 67];
$d = implode(',', $array);
$sql = "SELECT price FROM trade WHERE id IN($d)";
$query = mysqli_query($conn, $sql);
if($query){
while ($row = mysqli_fetch_assoc($query)) {
echo $row['price'].'<br>';
}
}
else {
echo mysqli_error($conn);
}

How to do two DB queries at once in PHP?

I have two queries but can I have them as just one
$sql = ("SELECT * FROM table WHERE title='$title' LIMIT 1");
$sql = ("UPDATE table SET views = views+1 where title='$title' ");
$query = mysql_query($sql) or die("Error Connecting To db");
At the moment the 2nd one works but not the first one.
This is your code:
$sql = ("SELECT * FROM table WHERE title='$title' LIMIT 1");
$sql = ("UPDATE table SET views = views+1 where title='$title' ");
$query = mysql_query($sql) or die("Error Connecting To db");
First, the first $sql will not run because you are overwriting the contents of that first $sql with new content in the next line.
Then just looking at your logic, here is your first query:
SELECT * FROM table WHERE title='$title' LIMIT 1
I assume that is to get the entry with the title equalling $title and nothing else, right? But then your next query is this:
UPDATE table SET views = views+1 where title='$title'
You are updating the value where title='$title' anyway. So the first query is not even needed. So problem solved, right? Well you might want to add the LIMIT 1 to the second query like this:
UPDATE table SET views = views+1 where title='$title' LIMIT 1
But honestly the logic of updating a DB based on whether an item title matches seems messy. What if two items have the same title? Yes, you are limiting things by 1 but by what criteria? If you have three items with the same title, which gets updated?
You need more differentiation for your app structure. But I think that is fair for what is essentially a newbie question.
Run the two queries separately
$sql1 = ("SELECT * FROM table WHERE title='$title' LIMIT 1");
$qry = mysql_query($sql1);
if (mysql_num_rows($qry) > 0)
{
while ($res = mysql_fetch_object($qry))
{
// -- contents --
}
$sql = ("UPDATE table SET views = views+1 where title='$title' ");
$query = mysql_query($sql) or die("Error Connecting To db");
}

Count numbers of checkboxes and update MySQL

I'm updating some MySQL data for specific entries selected through checkboxes, my code for that looks like this:
<?php
if($_POST['code_approve']){
for($i=0;$i<count($_POST['checkbox']);$i++){
$approval_id = $checkbox[$i];
$sql = "UPDATE table SET status='approved', used='processed' WHERE id='$approval_id'";
$result = mysql_query($sql);
}
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=table.php\">";
}
}
?>
Now I want to know how many checkboxes have been selected, and for every checkbox selected add 25 to table "members" row "balance".
I tried like this:
<?php
if($_POST['code_approve']){
for($i=0;$i<count($_POST['checkbox']);$i++){
$approval_id = $checkbox[$i];
$approvedamount = count($_POST['checkbox'])
$approvedx25 = $approvedamount * 25;
$sql = "UPDATE table SET status='approved', used='processed' WHERE id='$approval_id'";
$sql2 = "UPDATE members SET balance = + '$approvedx25'";
$result = mysql_query($sql);
}
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=table.php\">";
}
}
?>
But that didn't work at all, what's the proper way to do this ?
//EDIT
Please ignore this question, it worked, i just forgot to add the mysql_query.
Your update query should be something like this:
$sql2 = "UPDATE members SET balance = balance + ".$approvedx25;
The way you wrote it, the update in withing the for clause, thus executed once for every checkbox. I'm not sure you want that, since you already multiply by the number of checkboxes.
Also, mind, your second query ($sql2) is not executed in your code.

Check whether data is at table

I asked something about in_array() and I already got that working. But now I have a different problem:
I have a table that says which services are assigned to hosts: services_hosts(service_id, host_id).
How can I see if the service that is selected is already assigned to that host, also selected? Basically, I want to see if the specific line (service_id, host_id) already exists in that table.
EDIT:
The problem is that I want to compare in a separate file that has functions that connect to DB:
function addServiceToHost($service_name, $host_id)
{
$query = "INSERT INTO monitoring_hosts_services (service_id, host_id) values ((SELECT service_id FROM monitoring_services WHERE name = '".$service_name."'), '".$host_id."')";
$result = #pg_exec($this->conn, $query);
if ($row = pg_fetch_row($result))
{
"blabla error msg"
exit;
}
return $this->parseResultObj($result);
}
I might not unserstand your question correctly but would this do the trick:
SELECT * FROM ServerHostsTable WHERE service_id = '5' AND host_id = '8'
$query = ("SELECT * FROM ServerHostsTable WHERE service_id = '5' AND host_id = '8'")
if(mysql_num_rows($query)>0)
{
//the item is in the db
}
else
{
//not in the db
}
hope this helps
your question is not very clear, but from what I understand you want to test if a specific row is inserted into a database table. you could do this like this:
$result=mysql_query("SELECT service_id FROM services_hosts WHERE service_id=$theserviceid AND host=$thehostid");
if($row=mysql_fetch_row($result){
echo "already in the db";
} else {
echo "not in the db!";
}
I would run this query.
$sql = "SELECT COUNT(*) AS ret\n";
$sql.= "FROM services_hosts\n";
$sql.= "WHERE service_id = $service_id\n";
$sql.= "AND host_id = $host_id";
The result should be one row with one field (named ret):
0 - the service is not present on the host
1 - service is present on the host
enything else - there is a problem with table in database

Categories