Query multiple mysql rows and separate into variables after?
I am trying to select multiple rows from the database and then separate the rows into array values so I can use them throughout my code.
This is what I have right now...
$result = mysql_query("SELECT url, image, placement FROM advert
WHERE user='1'") or die(mysql_error());
//This grabs 3 rows with placement name equal to 'sideadtop','sideadmiddle','sideadbottom'
($row = mysql_fetch_array($result, MYSQL_NUM));
$keytop = array_search('sideadtop', $row);
$sideadtop['url'] =开发者_开发技巧= $row[$keytop]['url'];
$sideadtop['image'] == $row[$keytop]['image'];
$keymiddle = array_search('sideadmiddle', $row);
$sideadmiddle['url'] == $row[$keymiddle]['url'];
$sideadmiddle['image'] == $row[$keymiddle]['image'];
I am trying to get the url and image values for each ad placement value. I am not sure how the output for the mysql query is sent to php. Is it sent as a multideminsional array or just a array?
Should I be calling individual MySQL queries or is there an easy way to call multiple rows and than separate them after?
mysql_fetch_*
will only fetch one row. I think what you want is this:
$result = mysql_query("SELECT url, image, placement FROM advert WHERE user='1'")
or die(mysql_error());
$adverts = array();
while(($row = mysql_fetch_assoc($result))) {
$adverts[$row['placement']] = $row;
}
It will create an array like this:
Array(
'sideadtop' => Array(
'url' => ...,
'image' => ...,
'placement' => ...
),
'sideadmiddle' => Array(...),
'sideadbottom' => Array(...)
)
You can access the individual adverts with $adverts['sideadtop']
, $adverts['sideadmiddle']
, etc.
Imo this is a better approach than creating a variable for each element.
Calling mysql_fetch_assoc/mysql_fetch_array will get you one row of the data. You can then iterate this, to get all the rows.
I would tend to use mysql_fetch_assoc, for a small performance increase.
E.g.
$result = mysql_query("SELECT url, image, placement FROM advert
WHERE user='1'") or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$keytop[] = array_search('sideadtop', $row);
$sideadtop['url'][] == $row[$keytop]['url'];
$sideadtop['image'][] == $row[$keytop]['image'];
$keymiddle[] = array_search('sideadmiddle', $row);
$sideadmiddle['url'][] == $row[$keymiddle]['url'];
$sideadmiddle['image'][] == $row[$keymiddle]['image'];
}
I would also think about how you would like the resulting data structured, but you should get the gist.
精彩评论