I am trying to update rows in mysql, but I have to use a "for" loop for multiple update queries, which have multiple values in each query. The queries are like the following:
update table set column1='100',column2='140,column3='150' where id =1
update table set column1='120',column2='145,column3='154' where id =2
update table set column1='141',column2='148,column3='155' where id =3
I am using a "for" loop to run multiple queries with different id's, I want to run a single query to update all rows, but not by using "case". Is that possible?
you can use loop for generating dynamic query.
please have a look.
This might be helpful to you.
$data[] = array("column1"=>100, "column2"=>140, "column3"=>150, "id"=>1 );
$data[] = array("column1"=>120, "column2"=>145, "column3"=>154, "id"=>2 );
$data[] = array("column1"=>142, "column2"=>148, "column3"=>155, "id"=>3 );
foreach($data as $dat){
$query = "UPDATE table SET column1=".$dat['column1'].", column2=".$dat['column2'].", column3=".$da['column2']." WHERE id=".$dat['id'];
echo $query;
}
Why would you put the WHERE clause if you wanna update all the ID's? If you don't wanna update all the ID's you will have to do it in a for loop.
UPDATE tableName SET column1 = '100', column2 = '140', column3 = '150'
You can use WHERE IN(...) for this.
Eg:
update table set column1='100',column2='140,column3='150' where id IN (1,2,3)
Related
I have a database where I want to read a table row by row and then for each row I want to update a cell. I have written the below code but is there a better way of doing this ? Better way I mean it takes less time than my code.
Here is my code :
$List = 'some text...';
$SQL = "SELECT * FROM TABLE";
$res = mysqli_query($database, $SQL);
while($row = mysqli_fetch_assoc($res)){
if(strpos($List,$row['name']) !== false){
mysqli_query($database, "UPDATE TABLE SET `yes`=1 WHERE name='".$row['name']."'");
}else{
mysqli_query($database, "UPDATE TA SET `yes`=0 WHERE name='".$row['name']."'");
}
}
That approach is not the best one, the idea of SQL is to manage and be able to do that in a more efficient way. Instead of iterating each row and executing total rows +1 queries you can do only 2 queries and update the information.
for Example:
-- Update all to 0
UPDATE TABLE SET `yes`=0 ;
-- Update the one on the list to 1
UPDATE TABLE SET `yes`=1 WHERE name in ('value1','value2','value3');
This approach could save you a lot of execution time and be more efficient event on very large datasets.
i have 2 solution here
Solution 1 :
Copy the table and perform the update and rename the orginal table and also rename copy 1 table to original 1
table_1 copy to table_2
perform the operation on table_2
then rename table_1 to bkp_table_1
then rename table_2 to table_1
Solution 2
with the user select insert the data in new table which you what to update.
UPDATE table1 SET row1 =CONCAT( row1, 'word1, word2')
I want to add a condition to the query above.
I'm looking to add text values to row1 on table1, which already contains some texts, the query above does the trick, but additionally to that, I need to add a condition. I have another table called "table2", with a column, let's say "row2" that equals to "1". I need to run the query above IF row2 in table2 equals to 1.
I'm running the query directly on PHP MyAdmin
Thanks in advance.
$query = "SELECT `row2` FROM `table2`";
$res = mysqli_query($query);
$row = mysqli_fetch_array($res);
if($row['row2'] == 1)
{
//run your update table code: UPDATE table1 SET row1 =CONCAT( row1, 'word1, word2')
}
I make a mathematichs function in mysql. and give two result because it`s calculate from 2 records. this is the source :
$calculate= mysql_query("select markers_tujuan.lng,markers_tujuan.lat,open_list.lat, open_list.lng,
((SQRT((((markers_tujuan.lat-markers_tujuan.lng)*(markers_tujuan.lat-markers_tujuan.lng)) + ((open_list.lat-open_list.lng)*(open_list.lat-open_list.lng)))))+(sqrt((((markers_tujuan.lat-open_list.lat)*((markers_tujuan.lat-open_list.lat)))+((markers_tujuan.lng-open_list.lng)*((markers_tujuan.lng-open_list.lng)))))))
as hasil
from markers_tujuan, open_list");
$op=mysql_query("select * from open_list");
$line=mysql_fetch_assoc($op);
/* fetch associative array */
while ($row = mysql_fetch_assoc($calculate)) {
printf ("1(%s %s),(%s %s),%s <br> \n", $row["lng"], $row["lat"], $row["lat"], $row["lng"], $row["hasil"]);
$try=mysql_query(" UPDATE open_list SET hitung = '".$row["hasil"]."' ");
}
and the result is
but I didn`t understand why query in mysql updating same query
As others have pointed out, your UPDATE statement does not have a WHERE condition. Therefore, every single row in your table will be updated, each time:
mysql_query(" UPDATE open_list SET hitung = '".$row["hasil"]."' ");
You should specify the PRIMARY KEY while updating. In this case, it is the column id (I presume). Example:
UPDATE open_list SET hitung = 'example' WHERE id = '4'
You should add SELECT open_list.id,... on your first query and WHERE id = ' . $row['id'] in the update sentence.
I need to select category ids from my sql database.
I have a variable $product_id and for each product id there are three rows in a table that i need to select using PHP.
If I do "SELECT * FROM table_name WHERE product_id='$prodid'"; I only get the one on the top.
How can I select all three category_ids which contain the same product_id?
I suppose you are using PHP's mysql functions, is this correct? I am figuring that your query is actually returning all three rows but you aren't fetching all of them.
$sql = "SELECT * FROM table_name WHERE product_id='$prodid'";
$r = mysql_query($sql, $conn); //where $conn is your connection
$x = mysql_fetch_SOMETHING($r); //where something is array, assoc, object, etc.
The fetch function gives only one row at a time. You say you need three so it needs to be executed three times.
$x[0] = mysql_fetch_assoc($r);
$x[1] = mysql_fetch_assoc($r);
$x[2] = mysql_fetch_assoc($r);
OR this would be better
while($curRow = mysql_fetch_assoc($r)) //this returns false when its out of rows, returns false
{
$categoryIds[] = $curRow['category_id'];
}
If this doesn't do it then your query is actually returning only one row and we need to see your tables/fields and maybe sample data.
SQL seems to be correct, but Why do you store product_id in categories table? if it's one-to-many relation it would be better to store only category_id in products table.
The SQL query is correct for what you want to do. It will select all the records in table_name with the field product_id = $prodid (not only 1 or 3 but any that matches the variable)
To select a few records you should use the LIMIT keyword
You should look inside your table structure and the variable $prodid to find problems.
I'm trying to update multiple rows in one table in MySQL database by doing this. And its not working.
$query = "UPDATE cart SET cart_qty='300' WHERE cart_id = '21';
UPDATE cart SET cart_qty='200' WHERE cart_id = '23';
UPDATE cart SET cart_qty='100' WHERE cart_id = '24';";
mysql_query($query,$link);// $link is specified above
Anyone know what is wrong with this.
From the PHP documentation:
mysql_query() sends a unique query (multiple queries are not supported)
The ; separates SQL statements, so you need to separate the queries if you want to continue using the mysql_query function...
mysql_query can't use multiple queries.
The easiest thing is to just run them separately. I believe you can do multi query but I haven't tried it.
$updateArray = array(21=>300,23=>200,24=>100);
foreach($updateArray as $id=>$value)
{
$query = "UPDATE cart SET cart_qty='$value' WHERE cart_id = '$id'";
mysql_query($query,$link);// $link is specified above
}
This will accept a combination of IDs and their corresponding cart value. Looping though, it builds the query and executes it. The array can then come from a variety of sources (results from another query, form inputs or, as in this case, hard-coded values)
Update:
If you really need to execute all in one, heres the PHP info on multi query:
mysqli::multi_query
You can do it this way:
UPDATE table
SET col1 = CASE id
WHEN id1 THEN id1_v1,
WHEN id2 THEN id2_v1
END
col2 = CASE id
WHEN id1 THEN id1_v2,
WHEN id2 THEN id2_v2
END
WHERE id IN (id1, id2)
This example shows updating two different columns in two different rows so you can expand this to more rows and columns by cludging together a query like this. There might be some scaling issues that makes the case statement unsuitable for a very large number of rows.
You'll need to send them as separate queries. Why not add the queries as strings to an array, then iterate through that array sending each query separtely?
Also check this thread for another idea
This isn't the best method.. But if you need to do multiple queries you could use something like...
function multiQuery($sql)
{
$query_arr = explode(';', $sql);
foreach ($query_arr as $query)
{
mysql_query($query);
}
}
another example of a helper query
function build_sql_update($table, $data, $where)
{
$sql = '';
foreach($data as $field => $item)
{
$sql .= "`$table`.`$field` = '".mysql_real_escape_string($item)."',";
}
// remove trailing ,
$sql = rtrim($sql, ',');
return 'UPDATE `' . $table .'` SET '.$sql . ' WHERE ' .$where;
}
echo build_sql_update('cart', array('cart_qty' => 1), 'cart_id=21');