简体   繁体   English

输入字段单词到php数组

[英]Input field words to php array

Friends text box with autocomplete script (which supports multiple word completion from userstable "fullname" column) in registration form. 具有自动完成脚本的朋友文本框(在注册表单中支持从用户表“fullname”列中完成多个单词完成)。 Now Question 1: How to get names array from text input field and find id's of theese fulnames with php? 现在问题1:如何从文本输入字段获取名称数组并使用php查找theese fulnames的id? Question 2: How registration form will put theese id's to second (friends) table, if new users id unknown during registration? 问题2:如果注册期间新用户身份未知,注册表格如何将theese id列入第二(朋友)表? For example, if visitor writes "Tu" script finds from users table "Tural Teyyuboglu", completes it, adds comma, user can add as much he wants user names. 例如,如果访问者从用户表“Tural Teyyuboglu”中找到“Tu”脚本,则完成它,添加逗号,用户可以添加他想要的用户名。 Every time script works. 每次脚本都有效。 I want to get this usernames seperated by comma to php array, search theese usernames one by one for id's and add to friends table. 我希望将这个用户名用逗号分隔到php数组,逐个搜索theese用户名作为id并添加到friends表。 But second wuestion occurs? 但第二个猜测发生了吗? But how registration form will put theese id's to second (friends) table, if new users id unknown during registration? 但是,如果注册时新用户身份不明,注册表格如何将theese id列入第二(朋友)表?

Sorry for my bad english. 对不起,我的英语不好。 My idea: I have a database of users, each user has an autoincremented id number field, and various other fields with their details on. 我的想法:我有一个用户数据库,每个用户都有一个自动增加的ID号字段,以及各种其他字段及其详细信息。 I would like to store within the user record a field with an array of friends. 我想在用户记录中存储一个包含一系列朋友的字段。 I would like the most efficient way to store and be able to search each users 'friend id array' field and list the friends ids per user search. 我希望以最有效的方式存储并能够搜索每个用户的“朋友ID数组”字段并列出每个用户搜索的朋友ID。 assuming at some point there could be a million users of which each has a million 'friend ids' in their array, I dont think having them comma seperated would be efficient, any solutions? 假设在某个时刻可能有一百万用户,其中每个人的阵列中都有一百万个“朋友ids”,我不认为让它们以逗号分隔会有效,任何解决方案? could it be stored in a blob and searched bitwise? 它可以存储在blob中并按位搜索吗? (eg a bit per person, so a 1k blob can store up to a possible 1024 friend combinations) I think another table is the best solution. (例如每人一点,所以1k blob可以存储多达1024个朋友组合)我认为另一个表是最好的解决方案。 It is a many-to-many relationship, I've built a separate table for user friends: usrfrnd_tbl with columns UserFriendID (unique key), UserID, FriendID In i applied Jquery autocomplete to friends field of registration form: When visitor types name of existing user to this input field, first of all, script searches for name existence, completes it (if exists), adds comma. 这是一个多对多的关系,我为用户朋友建立了一个单独的表:usrfrnd_tbl,列为UserFriendID(唯一键),UserID,FriendID在我应用Jquery自动完成到朋友注册表单的字段:当访问者类型名称为现有用户到此输入字段,首先,脚本搜索名称存在,完成它(如果存在),添加逗号。 User can type second, third... existing usernames to this field, and everytime script will auto complete. 用户可以在此字段中键入第二个,第三个...现有用户名,并且每次脚本都将自动完成。 Now i want to create php file that will search for id's of these usernames, create array of id's, add it to table "usrfrnd_tbl" new users "FriendID" field in db table. 现在我想创建将搜索这些用户名的id的php文件,创建id的数组,将其添加到db表中的表“usrfrnd_tbl”新用户“FriendID”字段中。 Question: 1. How to do it? 问题:1。怎么做? Now, how to fetch array of id's of written names, and put to "friends" field of usr_table after submission of registration form? 现在,如何获取书面名称的id数组,并在提交注册表后提交给usr_table的“friends”字段? 2. I need only id of written name,and fullname. 我只需要书面名称和全名。 I don't need value.How can i delete it from jquery code? 我不需要value.How如何从jquery代码中删除它?

HTML HTML

<form action="index.php" method="post">      
<input class="std" type="text" name="friends" id="friends"/>
<input type="submit" name="submit">
</form>

Jquery jQuery的

$(function() {
    function split( val ) {
        return val.split( /,\s*/ );
    }
    function extractLast( term ) {
        return split( term ).pop();
    }

    $( "#friends" )
        // don't navigate away from the field on tab when selecting an item
        .bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                    $( this ).data( "autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        })
        .autocomplete({
            source: function( request, response ) {
                $.getJSON( "search.php", {
                    term: extractLast( request.term )
                }, response );
            },
            search: function() {
                // custom minLength
                var term = extractLast( this.value );
                if ( term.length < 2 ) {
                    return false;
                }
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( ", " );
                return false;
            }
        });
});

search.php search.php中

$db = new mysqli('localhost', 'user' ,'pass', 'db') or die(mysqli_errno());
$q = strtolower($_GET["term"]);
if (!$q) return;
$query =  $db->query("select id, fullname from usr_table where fullname like '$q%'")  or die(mysqli_errno());
$results = array();
while ($row = mysqli_fetch_array($query)) {$results[] = array ( "id" => $row[0] , "label" => $row[1], "value" => $row[1] );}
echo json_encode($results);

Well, I would prefer to implement things this way: 好吧,我更愿意用这种方式实现:

Every time the visitors accept an auto-complete, a hidden input field would be created, just like in this very simple template: 每次访问者接受自动完成时,都会创建一个隐藏的输入字段,就像在这个非常简单的模板中一样:

<input type="text" name="user[id]" value="Friend's name" />

The dynamic form would look like this after some auto-completes: 一些自动完成后,动态表单将如下所示:

<form>
    <input type="hidden" name="friends[14]" value="Stephen Hawking" />
    <input type="hidden" name="friends[22]" value="Josh Obama" />
    <input type="hidden" name="friends[19]" value="Julia Bin Laden" />
    <input type="submit" />
</form>

Your $_REQUEST data would end structured in this much much more elegant associative array: 您的$_REQUEST数据将在这个更优雅的关联数组中结束:

Array
(
    [friends] => Array
        (
            [14] => Stephen Hawking
            [22] => Josh Obama
            [19] => Julia Bin Laden 
        )

)

With that structured data in hands, there is no excuse for tricky PHP string manipulations. 有了这些结构化数据,就没有理由进行棘手的PHP字符串操作。 Also, I think this would lead to a much more reusable code. 此外,我认为这将导致更多可重用的代码。

Hope it helps ;] 希望能帮助到你 ;]

$usr_fullname = mysql_real_escape_string($_GET['usr_fullname']);
// other user information here

$friend_str = mysql_real_escape_string($_GET['friend_str']);

$sql = "
INSERT INTO usr_table 
    (`fullname`, `etc`) 
VALUES 
    ('$usr_fullname', etc)
";

$result = mysql_query($sql) or die(mysql_error());

$new_user_id = mysql_insert_id($result);

$friend_arr = explode(',', $friend_str);

foreach($friend_arr as $friend_name) {
    $friend_name = trim($friend_name);

    if (empty($friend_name)) {
        continue;
    }

    $sql = "
    SELECT id
    FROM usr_table
        WHERE `fullname` = '$friend_name'
    LIMIT 1
    ";

    $result = mysql_query($sql);

    if (!$result) {
        echo "$sql failed " . mysql_error();
        exit;
    }
    if (mysql_num_rows($result) == 0) {
        continue; // this person does not exist
    }

    $data = mysql_fetch_array($result);
    $friend_id = $data['id'];

    $sql = "
    INSERT INTO usrfrnd_table 
        (`user_id`, `friend_id`)
    VALUES
        ('$new_user_id', '$friend_id')
    ";

    mysql_query($sql);
}

If I'm assessing your application correctly, your autocomplete populates an input field with names. 如果我正确评估您的应用程序,您的自动填充会使用名称填充输入字段。 Because it is only populated with names, your form does not know the IDs that correspond to each name. 因为它只填充了名称,所以表单不知道与每个名称对应的ID。 What you need is a solution where the name will maintain it's ID. 你需要的是一个解决方案,名称将保持它的ID。

This is what I used: Facebook style JQuery autocomplete plugin 这就是我使用的: Facebook风格的JQuery自动完成插件

It is identical FB. 它是相同的FB。 You are able to add/remove names, and maintain their IDs. 您可以添加/删除名称,并维护其ID。

When your [POST] form is submitted, your populated input field will output as follows: 提交[POST]表单后,填充的输入字段将输出如下:

$_POST['friends'] = "24,54,67,7,9"; // comma-delimited list of corresponding IDs

Using PHPs explode function, you can get each ID and simply process your information per ID. 使用PHPs explode功能,您可以获取每个ID,并根据ID简单地处理您的信息。 Possibly, like so: 可能,像这样:

$personAddingFriendsID = 45; // arbitrary
$friends = explode(",", $_POST['friends']);

foreach ($friends AS $friendID) {
     $insertQuery = "INSERT INTO friendsMap SET friend1 = '$personAddingFriendsID', friend2 = '$friendID";
     //etc.. (not including SQL injection)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM