如何从表MySQLi中的每一列的末尾删除5个字符

时间:2016-07-01 08:53:39

标签: php mysql

我正在尝试遍历表中的每一行,并从一列的末尾删除5个字符。我编写了以下代码,但由于某种原因,它似乎删除了2个字符。

<?php
$connection = new mysqli('localhost', 'nawd_test', 'password', 'nawd_test');

if ($connection->connect_errno > 0) {
    die ('Unable to connect to database [' . $connection->connect_error . ']');
}

$sql = "SELECT *
        FROM test";  

if (!$result = $connection->query($sql)) {
    die ('There was an error running query[' . $connection->error . ']');
}

//Create an array to hold the values of id's already changed
$ids = [];
$newVals = [];

echo '<p>Fetching rows...</p>';
while ($row = $result->fetch_assoc()) {
    //Check / Add the id
    if (in_array($row['id'], $ids)) {
        echo '<p style="red"><strong>Error: Script has repeated itself!</strong></p>';
        break;
    }
    $ids[] = $row['id'];

    $rowName = $row['name'];
    $newName = substr($rowName, -1);
    $newName = rtrim($rowName,$newName);
    $newVals[] = $newName;
}

//Now loop and update
$newValID = 0;
foreach ($ids as &$id) {
    echo '<p>Updating row with ID ' . $id . '</p>';
    mysqli_query($connection, "UPDATE test SET name ='" . $newVals[$newValID] . "' WHERE id=" . $id);
    echo '<p>Column successfully changed "<em>' . $newVals[$newValID] . '</em>"</p>';
    $newValID++;
}

echo '<p style="color: green;"><strong>Script complete!</strong></p>';
?>

3 个答案:

答案 0 :(得分:1)

不要在php中执行此操作,您可以使用单个SQL查询执行此操作:

UPDATE test SET name = LEFT(name, LENGTH(name) - 5)

答案 1 :(得分:0)

更改

$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);

$newName = substr($rowName, 0, strlen($rowName) - 5);

通过您的工作方式,您无法预测到最后会删除多少个字符。 最小值为1,最大值为整个单词。

请阅读有关rtrimsubstr

的文档

答案 2 :(得分:0)

如果您想在查询中执行此操作,请尝试此操作:

update table1 set name=substr(name,-5,length(name))