I have this code:
if ($firearm != "") {
$sql_result5 = mysql_query("SELECT icon FROM db_firearms WHERE name='$firearm'", $db);
$rs5 = mysql_fetch_array($sql_result5); $firearm_icon=$rs5[icon];
}
if ($item != "") {
$sql_result5 = mysql_query("SELECT icon FROM db_items WHERE name='$item'", $db);
$rs5 = mysql_fetch_array($sql_result5); $item_icon=$rs5[icon];
}
if ($vehicle != "") {
$sql_result5 = mysql_query("SELECT icon FROM db_vehicles WHERE name='$vehicle'", $db);
$rs5 = mysql_fetch_array($sql_result5); $vehicle_icon=$rs5[icon];
}
if ($melee != "") {
$sql_result5 = mysql_query("SELECT icon FROM db_melee WHERE name='$melee'", $db);
$rs5 = mysql_fetch_array($sql_result5); $melee_icon=$rs5[icon];
}
This code is being refreshed every 10 seconds on a part of my page showing the players equipment. Would it be best to have this in one query, to save db resources?
If so, how would I write that? Would it be INNER JOINS? normal JOINS?
You'd use a union, with a bit of fireproofing in case you get no match on a name:
Code example to work around broken DB-design
$sql = "
(SELECT 'fire' as id, icon FROM db_firearms WHERE name='$firearm' LIMIT 1)
UNION ALL
(SELECT 'item' as id, icon FROM db_items WHERE name='$item' LIMIT 1)
UNION ALL
(SELECT 'vehi' as id, icon FROM db_vehicles WHERE name='$vehicle' LIMIT 1)
UNION ALL
(SELECT 'melee' as id, icon FROM db_melee WHERE name='$melee' LIMIT 1)
";
$result = mysql_query($sql);
if ($result) {
while ($row = mysql_fetch_array($result)) {
if ($row['id'] == 'fire') {$fireicon = $row['icon'];}
elseif ($row['id'] == 'item') {$itemicon = $row['icon'];}
elseif ($row['id'] == 'vehi') {$vehiicon = $row['icon'];}
elseif ($row['id'] == 'melee') {$meleeicon = $row['icon'];}
}
}
The union all
stops MySQL trying to eliminate duplicates, speeding up the query.
Better solution
You should really put all your icons in one table
TABLE icons
user_id
icon_type ENUM('gun','item','melee','vehicle')
icon blob
primary key (user_id, icon_type)
Now you can select
SELECT icon_type, icon FROM icons WHERE user_id = '$user_id';
But of course this really depends of the details of your application.
My point is just that UNION is a warning sign that you're doing something wrong or unusual
Would it be best to have this in one query, to save db resources?
No.