Updating a database column (vertically) with an array

时间:2016-07-11 22:16:27

标签: php mysql sql-update

I have a database table with the following structure. id column is added later. So all id cells are empty.

id  | song  | album | artist
-----------------------------
    | song1 | alb1  | art1
    | song2 | alb2  | art2
    | song3 | alb3  | art3
    | song4 | alb4  | art4
    | song5 | alb5  | art5

I have an array which holds the id values for the table. I'll be updating the table (the id column) with the values in the array. For example:

$array = [
    "C45Rm3fLGn",
    "ocIik81up2",
    "IcuSn9T77y",
    "tJv7AbF53r",
    "a9eZ6xYM5Y",
];

These items are unique random strings.

How should I proceed? I'm thinking about iterating the array and using UPDATE on each item.

$array = [
    "C45Rm3fLGn",
    "ocIik81up2",
    "IcuSn9T77y",
    "tJv7AbF53r",
    "a9eZ6xYM5Y",
];

$rows = $mysqli->query("SELECT * FROM songs")->fetch_all(MYSQLI_ASSOC);

for ($i = 0; $i < count($array); $i++) {
    $row = $rows[$i];
    $id  = $array[$i];
    $mysqli->query("UPDATE songs SET id = '$id' WHERE song = '{$row["song"]}' AND artist = '{$row["artist"]}'");
}

Is there a more preferable way?


UPDATE: I do not use auto increment and the id column didn't exist at the time of table was created. Now, I've added an id column. There are 300+ records. IDs of the records are unique random strings. Before I add another record to the database, every record needs to have a unique random string for its id, so that when I insert a new record, I can create a random string and check if it's unique or not by comparing it to the ids in the table.

At this stage, I just need to update the id column using an array. Array items are irrelevant.

2 个答案:

答案 0 :(得分:1)

Prepared statements are designed to be prepared once and executed many times, with a minimum of overhead. Using them is also an absolute necessity if the data you're inserting is user-generated.

It's been a long time since I've done anything with MySQLi (I strongly recommend looking at PDO for much simpler code) but this should work:

$array = [
    "C45Rm3fLGn",
    "ocIik81up2",
    "IcuSn9T77y",
    "tJv7AbF53r",
    "a9eZ6xYM5Y",
];

$rows = $mysqli->query("SELECT * FROM songs")->fetch_all(MYSQLI_ASSOC);
$stmt = $mysqli->prepare("UPDATE songs SET id=? WHERE song=? AND artist=?");

foreach ($array as $i=>$id) {
    $row = $rows[$i];
    $stmt->bind_param("sss", $id, $row["song"], $row["artist"]);
    $stmt->execute();
}

I would also recommend building your array such that it references the columns you're renaming. You're relying on both the database and the array being in the same order, which may not always be the case.

答案 1 :(得分:0)

Please try this query:

UPDATE `myTable` SET `id`= CONCAT(item-name, "-id");

Or you can set a counter like this:

UPDATE `myTable`, (SELECT @i := 0) c SET `id`= CONCAT(item-name, "-id-", @i:=@i+1)

I hope this will help you.