douchu2823 2012-09-18 17:30
浏览 16

更新mysqlDB的函数在foreach循环中不起作用

I two tables (authors and books) linked with the table "book authors".

The "book authors" table contains BookAuthorID, AuthorID and BookID, meaning I can have multiple books from the same author etc, and matching them is a doddle.

Unfortunately I messed up the ID field for the authors table and have created a new one that is primary and autoincrements. Now I need to populate a matching column in the "book authors" table with the new ids, matching them with the old ones.

I have the following function to update the "book authors" table...

function update_id($BookAuthorID, $NewAuthorID) {
$result = mysql_query("UPDATE `book authors` SET NewAuthorID='$NewAuthorID' WHERE BookAuthorID='$BookAuthorID'") or trigger_error(mysql_error()); }

I know this function works as I have tested it by creating a blank page with the function and two example variables ($BookAuthorID, $NewAuthorID) and it updated the table correctly.

Now I have the following code which finds every instance of each author, and then a foreach loop on each book matches the ids...

$result = mysql_query("SELECT * FROM authors");

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $AuthorID= $row["AuthorID"];

    $match = get_books($BookID);

    foreach ($match as $value) {    
        update_id($value["BookAuthorID"], $value["NewAuthorID"]);
    } 
}

the get_books function is as follows and works for the rest of the site...

function get_books($id) {
    $result = mysql_query("SELECT * FROM `book authors` WHERE AuthorID= $id") or trigger_error(mysql_error());
    $array = array();

    while($row_ids = mysql_fetch_assoc($result)){
        $array[] = $row_ids;
    }
return $array; 
}

I cant figure out why the function works outside the foreach loop, but does nothing inside (and no errors are generated).

  • 写回答

1条回答 默认 最新

  • dongyoulou4829 2012-09-18 19:57
    关注

    Couldn't you do something like:

    UPDATE `book authors`, authors 
    SET `book authors`.newauthorid = authors.newauthorid 
    WHERE `book authors`.authorid = authors.authorid;
    

    instead of looping?

    评论

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了