gpt4 book ai didi

php - 在单个属性中插入多个值

转载 作者:行者123 更新时间:2023-11-29 05:34:38 25 4
gpt4 key购买 nike

我在一个数据库中有两个表,

  tbl_language:                           tbl_users  lang_id    lang_name               user_id          user_name        user_lang  1          English                                   2          Spanish                                   3          German  4          Portuguese

I have PHP code to select languages from tbl_lang, Now I have a multiple select in a form where users can choose more than one languages. While inserting the values in database, I want to store multiple language values in one column/attribute. Where user_lang attribute would only store lang_ids of the tbl_language separated by comma(,).

Like

  tbl_users:  user_id          user_name        user_lang  1                 ABC              1,2  2                 XYZ              1,4

How to accomplish this using PHP and MySQL ?

I have sample code here:

<?php

$user_name = $_POST['user_name'];
$user_lang = $_POST['user_lang']; // user_lang as array from multiple select
$qry = ""; // I need help with this query

最佳答案

根据您的设置,考虑到 user_id 是一个自动递增的 PK:

$user_name = mysql_real_escape_string($_POST['user_name']);
$user_lang = mysql_real_escape_string(implode(',', $_POST['user_lang']);
$sql = "INSERT INTO tbl_users (`user_name`, `user_lang`) VALUES ('{$user_name}', '{$user_lang}');

但是,正如其他人所提到的,您可能应该寻找第 3rd 级表:

tbl_users_lang
user_id lang_id

并插入like(例如,没有错误处理,只是一个建议)

$user_name = mysql_real_escape_string($_POST['user_name']);
$sql = "INSERT INTO tbl_users (`user_name`) VALUES ('{$user_name}');"
mysql_query($sql);

$user_id = mysql_insert_id();
foreach ($user_lang as $lang) {
$lang = mysql_real_escape_string($lang);
$sql = "INSERT INTO tbl_users_lang (`user_id`, `lang_id`) VALUES ({$user_id}, '{$lang}');"
mysql_query($sql);
}

** 编辑 **

作为奖励,使用此查询,您可以获取任何给定用户的语言列表的逗号分隔行。我想你可能会感兴趣:

SELECT DISTINCT u.user_id, u.user_name, GROUP_CONCAT(l.lang_name) 
FROM `tbl_users` as u
LEFT JOIN `tbl_users_lang` as ul ON u.user_id = ul.user_id
LEFT JOIN `tbl_language` as l on ul.lang_id = l.lang_id
-- add WHERE clause here to filter (ex : WHERE u.user_name LIKE 'John%')

关于php - 在单个属性中插入多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11822321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com