Attaching categories from one table to entries in another MySQL

前端 未结 3 612
攒了一身酷
攒了一身酷 2021-01-23 15:31

I have a database which takes user submitted data, the entries from which I want to group under one or several of about 10 categories.

So for example, you add your entr

3条回答
  •  死守一世寂寞
    2021-01-23 16:00

    I agree with you that it's simple. Perhaps this will answer your questions.

    I assume that your form has check-boxes or a multi-select box to allow the user to select categories for his/her business. And that the "value" attribute of the check-box/select-box is set to the category ID, as stored in the categories table. So, now when the form is submitted, you'll get in the PHP script, along with other inputs from the form, an array with the IDs of the categories selected by the user. Let's call it $_POST['categories']

    METHOD 1:

    a. Run the query - INSERT INTO business ...

    b. read the ID of the last entry made into business table using either mysql_insert_id or mysqli->insert_id, depending on either you are using MySQL or MySQLi library. Suppose you store this ID in $busId

    c. From $_POST['categories'], generate a comma-separated string using implode(). Suppose you store this string in $strCategories

    d.

    INSERT INTO `tbl_works_categories` (`bus_id`, `category_id`)
    SELECT $busId, `category_id`
    FROM `categories`
    WHERE `category_id` IN ($strCategories);
    

    METHOD 2:

    Alternatively, you may as well loop through the POST array and generate INSERT query, like:

    $q = '';
    if (!empty($_POST['categories'])) {
        $q = 'INSERT INTO `tbl_works_categories` (`bus_id`, `category_id`) VALUES ';
        foreach ($_POST['categories'] as $categoryId) {
            $q .= '(' . $busId . ', ' . $categoryId . '),';
        }
    }
    $q = trim($q, ','); // to remove the trailing comma
    if (!empty($q)) {
        // execute query $q
    }
    

    Hope the above helps. I haven't tested any of the above codes, so you might need to do some debugging if anything is broken. Please feel free to ask if you've any questions.

提交回复
热议问题