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);
}

 

   // 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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.