Jump to content

Is there a better way to write this function?


c_shelswell

Recommended Posts

I was just wondering if there was a better way to write this. My query should return a few results and i'm adding it to an array in the foreach but i'm having to use an $i++; to add the next item to the array. The code works and returns what i'm after  just wondering if there's a slightly better way.

thanks

[code]function get_media_titles($mediaId)
{
$conn = db_connect();
$i=0;
foreach ($mediaId as $key => $id)
{
$query="select media.title from media left join purchases using(media_id) where purchases.media_id='$id' limit 1";
$result= mysql_query($query);
if (!$result)
return false;
$num_rows = @mysql_num_rows($result);

if ($num_rows == 0)
return false;

if($result)
{
$titles[$i] = mysql_result($result, 0, 'title');
}
$i++;
}
return $titles;
}[/code]
Link to comment
Share on other sites

You can improve this function in the following ways:
[list]
[*] Always initialize your arrays.
[*] You don't need to use the index, "$i". Just use the empty index, " [] ", which automagically adds an entry to the end of an array.
[*] Use the function mysql_fetch_assoc() instead of mysql_result()
[*] You don't need the "if ($result)" check since you've already returned when the $result as false
[/list]

[code]<?php
function get_media_titles($mediaId)
{
$conn = db_connect();
$titles = array();
foreach ($mediaId as $key => $id)
{
$query="select media.title from media left join purchases using(media_id) where purchases.media_id='$id' limit 1";
$result= mysql_query($query);
if (!$result)
return false;
$num_rows = @mysql_num_rows($result);

if ($num_rows == 0)
return false;
                $rw = mysql_fetch_assoc($result);
$titles[] = $rw['title'];
}
return $titles;
}
?>[/code]

Ken
Link to comment
Share on other sites

In this case it doesn't matter much, just personal preference, but when you're using many fields from the row, using one of the functions that fetches the entire row in one swell foop ( :) ), is quicker and more efficient that getting each field one at a time.

Ken
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.