Originally posted by Gav
Hi,
function display_contents($table, $session) {
$count = 0;
$query = "SELECT * FROM $table WHERE session='$session'";
$result = mysql_query($query);
while ($row = mysql_fetch_object($result)) {
$contents['quantity'][$count] = $row->quantity;
$contents['title'][$count] = $row->title;
$contents['code'][$count] = $row->code;
$count++;
}
return $contents;
}
THNKS in advance [/B]
This is an observation, and not necessarily part of a solution, but I was thinking your data model could be improved by grouping by record, rather than by field. I.e. use
$contents[$count]['quantity'] = $row->quantity;
$contents[$count]['title'] = $row->title;
$contents[$count]['code'] = $row->code;
Then each record would be represented by a single intact array, such as $contents[4].
My personal style would tend to make the function look more like:
function display_contents($table, $session) {
$query = "SELECT quantity,title,code FROM $table WHERE session='$session'";
$result = mysql_query($query);
while ($row = mysql_fetch_object($result)) {
$contents[]=array(
'quantity'=>$row->quantity,
'title'=>$row->title,
'code'=>$row->code
);
}
return $contents;
}
or even
function display_contents($table, $session) {
$query = "SELECT quantity,title,code FROM $table WHERE session='$session'";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
$contents[]=$row;
}
return $contents;
}
(It wouldn't do to fold up $row and use while($contents[]=...) because then $contents would end up with a spurious false entry on the end.)
Further, if I had a unique identifier for the rows, I'd index $contents by that, instead of just a 0-based index, to make it an associative array.
But that's just me. Feel free to be different 🙂
To turn an $array into a string suitable for a form hidden field (why not use sessions?), htmlspecialchars(serialize($array)) would do the trick. If you use ' to delimit your html tag attribute values, then htmlspecialchars(...,ENT_QUOTES) is necessary (Also look at htmlentities() for a more thorough encoding). Serialize() converts PHP variable contents into strings, and htmlspecialchars() deals to characters that have a special meaning in html (and gee, I'd never have figured that out if I hadn't been told🙂) To convert back there's no unhtmlspecialchars() function, because PHP's CGI frontend will automagically do the trick. You just need to unserialize() to recreate the variable and its contents.