开发者

Input field words to php array

Friends text box with autocomplete script (which supports multiple word completion from userstable "fullname" column) in registration form. Now Question 1: How to get names array from text input field and find id's of theese fulnames with php? Question 2: How registration form will put theese id's to second (friends) table, if new users id unknown during registration? 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. 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. But second wuestion occurs? But how registration form will put theese id's to second (friends) table, if new users id unknown during registration?

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. 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. 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? could it be stored in a blob and searched bitwise? (e.g 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. 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. 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. Question: 1. How to do it? Now, how to fetch array of id's of written names, and put to "friends" field of usr_table after submission of registration form? 2. I need only id of written name,and fullname. I don't need value.How can i delete it from jquery code?

HTML

<form action="index.php" method="post">      
<input class="std" type="text" name="friends" id="friends"/>
<input type="submit" name="submit">
</form&g开发者_StackOverflow中文版t;

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

$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:

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. 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. What you need is a solution where the name will maintain it's ID.

This is what I used: Facebook style JQuery autocomplete plugin

It is identical FB. You are able to add/remove names, and maintain their IDs.

When your [POST] form is submitted, your populated input field will output as follows:

$_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. 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)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜