Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Substring headaches

  • This topic is empty.
Viewing 8 posts - 1 through 8 (of 8 total)
  • Author
    Posts
  • #40791

    Hey yall,

    I’m writing a function.

    The parameter it takes is a string, with the anatomy of numbers in an increasing order, separated by periods. One such string might look like this:

    1.4.12.56

    With any number of numbers it wishes to have.

    Now, I also have an key-value array defined, in which the keys are integer values, which correspond to strings. for example:

    $array = array (
    1 => “oranges”,
    2 => “apples”,
    3 => “pears”
    );

    That is a very shortened version of my 63 key-value pairs long array. (And BTW, I wasn’t sure on this…it is valid to use integers as keys or must you use strings?)

    Anyway, now that we have the string and array, I am trying to write a function that takes the string, chops it up into pieces, which are divided by the periods, looks at the array, utilizes foreach (at least that’s what I’m thinking) to grab each value corresponding to the key, and make a new array full of the strings and return that.

    If I wasn’t clear enough,

    if I put in a string, 1.3, it should return me an array with the contents “oranges”, “pears”.

    I have written a function for coming from an array to this number sequence, to store it in the database, but I cannot reverse my own doing -_-

    I specifically got stuck on the chopping up the string…I don’t really know how to divide at periods, but I guessed it would be easy enough. (Maybe too much Jahooma’s Logicbox? :P) If I should be making the string input another format, please suggest. I’m open to ideas :)

    Thanks,
    Red

    #114282
    JoniGiuro
    Participant

    Why are you using an integer key for the $array ? An array already has integer keys.
    sorry I didn’t notice it was posted in php and I thought you were speaking about js ($array, stupid me..), but you might be able to do pretty much the same thing with php

    http://jsfiddle.net/XmjRC/

    see here:
    http://php.net/manual/en/function.split.php

    #114304
    MrSoundless
    Member
    #114311
    __
    Participant

    ⬑ good solution.

    Regarding integer keys, yes, it’s perfectly legal, and useful when you might need particular key values (instead of starting at `0`).

    #114388
    __
    Participant

    First:

    If your page is “not loading,” that probably means you have error reporting disabled. You should enable error reporting during development so you don’t have to guess at what’s going wrong.

    In your php.ini file, find these settings and comment them out (i.e., prepend them with a `;` – **do not** delete them, you’ll want to restore them when you’re done with your debugging):

    ;error_reporting = {this might be any of several values}
    ;display_errors = Off
    ;display_startup_errors = Off

    then give them these values:

    error_reporting = E_ALL
    display_errors = On
    display_startup_errors = On

    Next, the obvious problem with your function is that `$wares` does not exist.

    It’s also very difficult to figure out what you’re *trying* to do – your function seems to be very tightly related to the data structures you expect to receive. Can you show an example of what your arrays [are supposed to] look like?

    #114512
    __
    Participant

    > still it doesn’t load. Chrome states “HTTP 500 Internal Server Error.”

    some hosts are more zealous about hiding errors. Ask them about it. Also ask about where your error log file is; PHP errors should be being logged there.

    > $wares does exist, …

    Not in your function, it doesn’t.

    Read up about “scope” in PHP. Variable scope is, basically, the “space” within a script where variables “exist.” Classes and functions in PHP have their own scope. Example:

    # this is the “global scope.”
    # if you declare $myvar here,
    # it’s available anywhere in the global scope.

    if( condition ){
    # conditional blocks, loops, etc. don’t have their own scope
    # $myvar is available here.
    }

    function myfunc(){
    # functions *do* have their own scope –
    # $myvar does not exist here!

    $myvar = “other value”;
    # if you declare $myvar inside the function,
    # it **is not** the same as the $myvar in the global scope.
    print $myvar;
    # local (myfunc) scope – prints “other value”
    }
    print $myvar;
    # global scope – prints “some value”

    To use a global variable inside a function, you need to either pass it in (preferred), or import it from the global scope.

    ## preferred ##
    function pass( $arg ){
    /* do stuff */
    }
    # when you pass $myvar to the function, like so –
    pass( $myvar );
    # it is available inside the function as “$arg”.

    # import the variable you need into the function
    function import_var(){
    global $myvar;
    # now the global $myvar is available inside the function.
    /* do stuff */
    }
    # this method is less preferable,
    # since you cannot be sure of the current state of the global $myvar
    # (or if it even exists when the function is called)

    > I want two functions: 1. takes an array (just values array, no keys), cycles through them, finds their key in the $wares array, and appends it to a string. The wares are separated by a period. So you get a string like 1.4.28 that I can store in the database. 2. takes the string from the database and reverts the string back to an array.

    Before going ahead with this, consider that you’re defeating the purpose of using a database by encoding a bunch of data and storing it in a single field – you’re effectively making it “invisible.”

    What if you wanted to find records of Oranges (“1”)? You’d have to extract all the data, convert it back into an array, and *then* search for Oranges. If you have a large dataset, that’s a huge waste of time. If you’d stored “Oranges” in the database directly, MySQL could’ve searched *for* you (that’s its purpose in life, after all).

    But anyway,

    If you want to represent an array as a string (e.g., so you can store it in the DB), there’s already a function to do that:

    $array = array( ‘oranges’,’apples’,’pears’ );

    # convert $array into a string value
    $str = serialize( $array );

    # now you can save it to the DB, in your SESSION, whatever
    # to convert it back, use:
    $array = unserialize( $str );

    # you can also use JSON –
    $jsonstr = json_encode( $array );

    # and convert it back into an array
    $array = json_decode( $jsonstr,true );

    #114610

    Hi there – looks like based on what you’re trying to do you may benefit from using 2 more tables in your database. Specifically – you could build these tables:

    **ware** & **profileware**

    **ware** should have an ID and a VARCHAR field for the name of the ware

    **profileware** should have an ID and a wareID and a profileID and a TINYINT called _isbuying_ that is 1 for buying and 0 for selling (or equivalent)

    **ware** will keep track of all of the wares available, should just be the 126 listed out. and **profileware** will keep track of the relationship between the profile (user) and the ware. so if my profileID is 5 and i want to buy iron (wareID: 1) and sell sheep (wareID: 4) there should be two rows in profileware for me:

    ID: 1, profileID: 5, wareID: 1, isbuying: 1
    ID: 2, profileID: 5, wareID: 4, isbuying: 0

    then in your HTML markup – name each of the wares something like this:

    The value corresponds to the ID of the ware, and ALL of the checkboxes can have the same name “buyware[]”

    When the user saves the data, you will have an array of all of the wares they have selected. In the DB erase all of the profileID records from profileware and insert new records for each of the wares they have selected by doing a foreach on $_POST – also be sure to keep track of whether they are buying or selling so buying checkboxes are called name=”buyware[]” and selling are name=”sellware[]” – etc.

    Is this making sense? Then read into MySQL JOINs and reap the rewards of relational databases! :)

    #114611
    __
    Participant

    Am I understanding correctly that `$sell` and `$buy` are the values returned by `serialize()`?

    `serialize()` returns a string, which needs to be delimited by single quotes in a MySQL query. The string may also include characters (e.g., ` ‘ `) that need to be escaped before being used in your query.

    $str = serialize( $array );
    # assuming $DB is an instance of mysqli
    $x_str = $DB->real_escape_string( $str );
    $query = “UPDATE `profile` SET `col`=’$xstr’ …”;

    Honestly, though, you could be doing this in a much less complicated way.

    .1. define *all* key=>ware pairs (including “excellent” wares):

    $wares = array(
    1 => ‘iron’
    ,2 => ‘oranges’
    // . . .
    ,64 => ‘excellent iron’
    ,65 => ‘excellent oranges’
    // . . .
    );

    .2. in your form, use the keys as the values in the first place:

    <.form>


    If you’re not already doing so, you can use PHP to generate this form (which would be easier, and much less error-prone, than writing it by hand):

    # loop through $wares array and create HTML inputs
    foreach( $wares as $key => $ware ){
    $checkbox[] = ‘ ‘. $ware;
    }

    .3. now, when your user submits the form, you have a pre-made array containing the keys of the items they’ve checked, which you can serialize directly:

    $sellStr = serialize( $_POST );
    $x_sellStr = $DB->real_escape_string( $sellStr );
    $query = “UPDATE `profile` SET `selling`=’$x_sellStr’ . . .”;

    Simpler, quicker, less error-prone.

    ********************
    ### Edit

    I missed @thatericsmith ‘s reply.

    What he’s describing is the same thing I was talking about in my first reply – *normalization*. It allows the database to “understand” the values you’re storing, rather than storing a big ugly string that has to be given back to PHP before it can be searched.

Viewing 8 posts - 1 through 8 (of 8 total)
  • The forum ‘Back End’ is closed to new topics and replies.