我需要更新整个数据库中的列值。包含特定字符串(例如,clie_id列中的id)的所有列都必须具有大写的值。换句话说,所有ID都必须大写。我知道如何对单个表执行此操作,但是有没有办法对所有表执行此操作? 好吧,看来现在一切都很好。我对嵌套循环有问题。我需要执行类似$ s3 = $ s1 + $ s2的操作来获取一个查询,但是我似乎无法正确执行。 代码更新。我必须在屏幕上打印:UPDATE'tablename'SET'columnname'= UPPER(columnname)或如果同一表中有多个列UPDATE'tablename'SET'columnname'= UPPER(columnname),'columnname1'= UPPER (columnname1)等。谢谢!
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tabledb";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//get table names
$sqlTables = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA= 'tabledb'";
//get column names
$sqlColumns = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%UUID%'";
// Prepare statement
$stmtTables = $conn->prepare($sqlTables);
$stmtColumns = $conn->prepare($sqlColumns);
// execute the query
$stmtTables->execute();
$stmtColumns->execute();
while ($rowTables = $stmtTables->fetchAll(PDO::FETCH_NUM) AND ($rowColumns=$stmtColumns->fetchAll(PDO::FETCH_NUM))) {
$tables = $rowTables;
$columns = $rowColumns;
}
foreach($tables as $table){
foreach ($table as $val) {
$s1 = "UPDATE ".$val.", <br>";
print_r($s1);
}
}
foreach($columns as $column) {
foreach ($column as $val2) {
$s2 = "SET ".$val2." = UPPER ($val2), <br> ";
print_r($s2);
}
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
答案 0 :(得分:2)
首先,您需要使用以下查询获取所有表
SELECT table_name FROM information_schema.tables where table_schema='your_database_name';
即
$tables = "SELECT table_name FROM information_schema.tables where table_schema='DBNAME'";
echo'<pre>';print_r($tables);
foreach ($tables as $table) {
$columns = "SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema='DBNAME' AND table_name='".$table->table_name."'";
echo'<pre>';print_r($columns);die;
foreach($columns as $column){
//Be careful with this
//$this->db->query("UPDATE ".$table->table_name." SET ".$column->COLUMN_NAME." = UPPER(".$column->COLUMN_NAME.")");
}
}
更新后的代码,请替换您的DBNAME,请小心我在这里使用对象数组的数组