dongpang2483 2014-01-03 20:33
浏览 46

PHP / MySQL从阵列中的多个结果运行函数

I'm not sure that I have the terminology correct but basically I have a website where members can subscribe to topics that they like and their details go into a 'favorites' table. Then when there is an update made to that topic I want each member to be sent a notification.

What I have so far is:

$update_topic_sql = "UPDATE topics SET ...My Code Here...";
$update_topic_res = mysqli_query($con, $update_topic_sql)or die(mysqli_error());

$get_favs_sql = "SELECT member FROM favourites WHERE topic = '$topic'";
$get_favs_res = mysqli_query($con, $get_favs_sql);

//Here I Need to update the Members selected above and enter them into a notes table

$insert_note_sql = "INSERT INTO notes ....";

Does anyone know how this can be achieved?

  • 写回答

1条回答 默认 最新

  • du7979 2014-01-05 00:32
    关注

    Ok, so we've got our result set of users. Now, I'm going to assume from the nature of the question that you may be a bit of a newcomer to either PHP, SQL(MySQL in this case), web development, or all of the above.

    Your question part 1:

    I have no idea how to create an array

    This is easier than what you may think, and if you've already tried this then I apologize, I don't want to insult your intelligence. :)

    Getting an array from a mysqli query is just a matter of a function call and a loop. When you ran your select query and saved the return value to a variable, you stored a mysqli result set. The mysqli library supports both procedural and object oriented styles, so since you're using the procedural method, so will I.

    You've got your result set

    $get_favs_res = mysqli_query($con, $get_favs_sql);
    

    Now we need an array! At this point we need to think about exactly what our array should be of, and what we need to do with the contents of the request. You've stated that you want to make an array out of the results of the SELECT query

    For the purposes of example, I'm going to assume that the "member" field you've returned is an ID of some sort, and therefore a numeric type, probably of type integer. I also don't know what your tables look like, so I'll be making some assumptions there too.

    Method 1

    //perform the operations needed on a per row basis 
    while($row = mysqli_fetch_assoc($get_favs_res)){
        echo $row['member'];
    }
    

    Method 2

    //instead of having to do all operations inside the loop, just make one big array out of the result set
    
    $memberArr = array();
    while($row = mysqli_fetch_assoc($get_favs_res)){
        $memberArr[] = $row;
    }
    

    So what did we do there? Let's start from the beginning to give you an idea of how the array is actually being generated. First, the conditional in the while loop. We're setting a variable as the loop condition? Yup! And why is that? Because when PHP (and a lot of other languages) sets that variable, the conditional will check against the value of the variable for true or false.

    Ok, so how does it get set to false? Remember, any non boolean false, non null, non 0 (assuming no type checking) resolves to true when it's assigned to something (again, no type checking).

    The function returns one row at a time in the format of an associative array (hence the _assoc suffix). The keys to that associative array are simply the names of the columns from the row. So, in your case, there will be one value in the row array with the name "member". Each time mysqli_fetch_assoc() is called with your result set, a pointer is pointed to the next result in the set (it's an ordered set) and the process repeats itself. You essentially get a new array each time the loop iterates, and the pointer goes to the next result too. Eventually, the pointer will hit the end of the result set, in which case the function will return a NULL. Once the conditional picks up on that NULL, it'll exit.

    In the second example, we're doing the exact same thing as the first. Grabbing an associative array for each row, but we're doing something a little differently. We're constructing a two dimensional array, or nested array, of rows. In this way, we can create a numerically indexed array of associative arrays. What have we done? Stored all the rows in one big array! So doing things like

    $memberArr[0]['member'];//will return the id of the first member returned
    $memberArr[1]['member'];//will return the id of the second member returned
    $lastIndex = sizeof($memberArr-1);
    $memberArr[$lastIndex]['member'];//will return the id of the last member returned.
    

    Nifty!!!

    That's all it takes to make your array. If you choose either method and do a print_r($row) (method 1) or print_r($memberArr) (method 2) you'll see what I'm talking about.

    You question part 2:

    Here I Need to update the Members selected above and enter them into a notes table

    This is where things can get kind of murky and crazy. If you followed method 1 above, you'd pretty much have to call

    mysqli_query("INSERT INTO notes VALUES($row['member']);
    

    for each iteration of the loop. That'll work, but if you've got 10000 members, that's 10000 inserts into your table, kinda crap if you ask me!

    If you follow method two above, you have an advantage. You have a useful data structure (that two dim array) that you can then further process to get better performance and make fewer queries. However, even from that point you've got some challenges, even with our new processing friendly array.

    The first thing you can do, and this is fine for a small set of users, is use a multi-insert. This just involves some simple string building (which in and of itself can pose some issues, so don't rely on this all the time) We're gonna build a SQL query string to insert everything using our results. A multi insert query in MySQL is just like a normal INSERT except for one different: INSERT INTO notes VALUES (1),(2),(x) Basically, for each row you are inserted, you separate the value set, that set delineated by (), with a comma.

    $query = 'INSERT INTO notes VALUES ';
    //now we need to iterate over our array. You have your choice of loops, but since it's numerically indexed, just go with a simple for loop
    $numMembers = sizeof($memberArr);
    for($i = 0; $i < $numMembers; $i++){
        if($i > 0){
            $query .= ",({$membersArr[$i]['member']})";//all but the first row need a comma
        }
        else {
            $query .= "({$membersArr[$i]['member']})";//first row does not need a comma
        }
    
    }
    
    mysqli_query($query);//add all the rows.
    

    Doesn't matter how many rows you need to add, this will add them. However, this is still going to be a costly way to do things, and if you think your sets are going to be huge, don't use it. You're going to end up with a huge string, TONS of string concats, and an enormous query to run.

    However, given the above, you can do what you're trying to do.

    NOTE: These are grossly simplified ways of doing things, but I do it this way because I want you to get the fundamentals down before trying something that's going to be way more advanced. Someone is probably going to comment on this answer without reading this note telling me I don't know what I'm doing for going about this so dumbly. Remember, these are just the basics, and in no way reflect industrial strength techniques.

    If you're curious about other ways of generating arrays from a mysqli result set: The one I used above

    An even easier way to make your big array but I wanted to show you the basic way of doing things before giving you the shortcuts. This is also one of those functions you shouldn't use much anyway.

    Single row as associative(as bove), numeric, or both.

    Some folks recommend using loadfiles for SQL as they are faster than inserts (meaning you would dump out your data to a file, and use a load query instead of running inserts)

    Another method you can use with MySQL is as mentioned above by using INSERT ... SELECT But that's a bit more of an advanced topic, since it's not the kind of query you'd see someone making a lot. Feel free to read the docs and give it a try!

    I hope this at least begins to solve your problem. If I didn't cover something, something didn't make sense, or I didn't your question fully, please drop me a line and I'll do whatever I can to fix it for you.

    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站