Jump to content

Foreach item in array query MySQL database trouble


raistrick

Recommended Posts

Hi All,

 

First time posting here. I've googled the problem, but can't seem to find a response that's the same.

 

All I want to do is have a list of id numbers and for each id number in the array, submit a MySQL query to retrieve information relating to the id number.

 

When I execute the code below however, I end up with only the last item in the array being printed in the echo statement.

 

Any clues?

 

Thanks,

 

// get array of ids
$ids = getIDs($ids); 

// loop through input list
foreach ($ids as &$id) {
	getVarDetails($id);
}

function getVarDetails($local)
{ 
	$con = mysql_connect('localhost:3306', 'root', '********');
	if (!$con)
	{
		die('Could not connect: ' . mysql_error());
	}

	// set database as Ensembl
	mysql_select_db("Ensembl", $con);

	$result = mysql_query("SELECT * FROM variations WHERE name = '$local' LIMIT 1");
	$row = mysql_fetch_array($result)

	while($row = mysql_fetch_array($result))
	{
		echo $row['name'] . " " . $row['id'];
		echo "<br />";
	}

	// close connection
	mysql_close($con);
}

 

Link to comment
Share on other sites

   // get array of ids
   $ids = getIDs($ids); 
   //pass array to getVarDetails
   getVarDetails($id);

   function getVarDetails($local)
   { 
      $con = mysql_connect('localhost:3306', 'root', '********');
      if (!$con)
      {
         die('Could not connect: ' . mysql_error());
      }

      // set database as Ensembl
      mysql_select_db("Ensembl", $con);
      // implode array into comma dilimetered string and use MySQL IN to select all matching rows
      $result = mysql_query("SELECT * FROM variations WHERE name IN  ( '". implode(', ', $local) . " ) ");
      // loop through results using assoc ( to fetch string keys rather than string and numerical indexed keys)
      while($row = mysql_fetch_assoc($result))
      {
         echo $row['name'] . " " . $row['id'];
         echo "<br />";
      }

      // close connection
      mysql_close($con);
   }

 

 

implode

mysql_fetch_assoc

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.