Forums

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

Home Forums Back End Substring headaches Re: Substring headaches

#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.