我在数据库表中有一组记录,其中一列有字符串值。类似HeyHelloWorld1
或HeyGoodDayWorld2
或HeyHowdyWorld32
的内容。我需要将它们全部更改为GoodEveningWorld
(以及字符串末尾的任何内容)。我正在尝试运行脚本,但这需要太长时间,我想知道是否有人知道实现这个的最快方法
剧本:
$con=mysqli_connect("localhost","user","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$str_to_look_for = 'Hey';
$new_str = 'GoodEvening';
$result = mysqli_query($con,"SELECT * FROM table1 WHERE item LIKE '%$str%'");
if(!$result) echo "No records found?";
else
{
echo " Found ".mysqli_num_rows($result)." rows<br/>... Executing script...";
while($row = mysqli_fetch_array($result))
{
$val = strstr($row['item'], '/World');
$new_val = $new_str.$val;
$id = $row['ID'];
insert($new_val, $id, $con);
}
echo " DONE!";
}
function insert($x, $id, $con)
{
$result = mysqli_query($con,"UPDATE table1 SET item = '$x' WHERE ID = '$id'");
if (!$result) echo "missed..<br/>";
}
答案 0 :(得分:1)
查看MySQL String functions并考虑直接在数据库中替换它。
UPDATE table1
SET item =
CONCAT(
'GoodEvening',
SUBSTRING( item, INSTR( item, 'World') )
)
这适用于World,而不仅仅是HelloWorld或HayWorld。