mysql update of update multiple records at one time
- 2020-06-19 11:49:59
- OfStack
I encountered a problem in my work: I had to update a data table.
This table was created by myself and has seven fields, id, name, package, and so on
When I created it, because I stored the name and package information in two text files,
So I used the Insert method, and I inserted all the name into the database once.
name is all imported into the database, but my package is not, so I still want to use the insert method to insert it, but it doesn't work.
This is a good time to use the update method. The idea of updating multiple pieces of information once is as follows:
UPDATE table_name
SET field_name = CASE other_field
WHEN 1 THEN 'value'
WHEN 2 THEN 'value'
WHEN 3 THEN 'value'
END
WHERE id IN (1,2,3)
The test code is as follows:
<?php
/*
*function: insert app's apk ,logo_url, document_title,app_desc,package_name
* into talbe atable use database db .
*/
//connect database catx.
$server='localhost';
$user='root';
$passwd='root';
$port='3306';
$dbname='catx';
$link=mysql_connect($server,$user,$passwd);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
else echo "Connected successfully\n";
mysql_select_db("db",$link);
//set init variable and start time
$st=microtime_float();
$table="pydot_g";
$path = "txt";
$fname_package_name = "package_name.txt";
//
$handle= @fopen($path."/".$fname_package_name, "r");
$i=1;
$sql = "UPDATE pydot_g SET package_name = CASE id ";
$ids="";
while(($buf[$i]=fgets($handle,512))!==false){
$sql .= sprintf("WHEN %d THEN '%s' ", $i, $buf[$i]); // Joining together SQL statements
$ids .= sprintf("%d,",$i);
$i++;
}
//$ids=implode(',',$ids);
$ids.=$i;
$sql .= "END WHERE id IN ($ids)";
echo $sql;
mysql_query($sql);
fclose($handle);
mysql_close($link);
//echo the results and total time used
$et=microtime_float();
$t=$et-$st;
echo "\r\ninsert into talbe ",$table," ",$i,"times;\r\n";
echo "Total time $t seconds.\r\n";
//function calculate time ,return a float number
function microtime_float(){
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
?>