简体   繁体   English

php,sql - 如何更改一列中的值并将其插入到另一列中

[英]php,sql - how to alter values from one column and inserting it into other

I wanna get the values from a column column1 and delete all the (spaces , %20, %2520, _ (underscore), - (hyphen) and . (dot)) from it and save the values to the corresponding place in other column2 .我想从列column1获取值并从中删除所有(空格、%20、%2520、_(下划线)、-(连字符)和 .(点))并将值保存到其他column2的相应位置.
Is this the right way to do it?这是正确的方法吗? will this even work?这甚至会起作用吗?

$conn = new mysqli($servername, $username, $password,$dbname);

$sql= "SELECT column1 FROM table" ;

$result = $conn->query($sql);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {


    $x= $row["column1"] ;


$find=array(" ","%20","%2520",".","-","_");
$x= str_replace($find,'',$x);


               $sql2 ="INSERT INTO table
             ( column2 )
             VALUES
             ( '$x' )";

              if ($conn->query($sql2) === TRUE) {
               echo "Record Created <br>";

                }

              else {
               echo "Error creating Record: " . $conn->error;
               }

    }
} else {
    echo "0 results";
}
$conn->close();

You need to Update not Insert .您需要Update而不是Insert

Use REPLACE function to remove the unwanted characters in your column使用REPLACE函数删除列中不需要的字符

First run select and check whether everything is fine then run update首先运行select并检查是否一切正常,然后运行update

SELECT column1,
       Replace(Replace(Replace(Replace(Replace(Replace(column1, ' ', ''), '%2520', ''), '%20', ''), '_', ''), '-', ''), '.', '') AS column2
FROM   yourtable 

UPDATE tablename
SET    column2 = Replace(Replace(Replace(Replace(Replace(Replace(column1, ' ', ''), '%2520', ''), '%20', ''), '_', ''), '-', ''), '.', '') 

First Step第一步

UPDATE table SET column1 = column2

Second Step第二步

UPDATE table SET column2 = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(column2, ' ', '') , '%20', '') ,'%2520', ''), '.', '') , '-', '') , '_', '')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM