0

I'm runing a query to pull some movie data from a source table to import into a new database structure. I'm then looping through the results using mysql_fetch_object and parsing data, calling external functions, etc to add the genres,actors,etc... to other tables in the database.

In one of my functions that I'm calling makes a query to a different table within the same database. I'm then getting a "not a valid MySQL-Link resource" on that query.

Is there anything that would cause issues doing this?

Here's some code on how the error is occuring:

function doThis($thing) { 
   mysql_query("SELECT derp FROM herp WHERE sherp = $thing",$db)or die(mysql_error()); 
}

$query = mysql_query("SELECT foo FROM bar",$db);
while($row = mysql_fetch_object($query)) {
   doThis($row->awesome);
}

This is essentially what I'm doing and I'm getting an error and don't know why.

Something of note may be that I'm connecting to 2 databases during this process. The database I'm pulling data from and the database I'm importing into.

Thanks!

LeGrande
  • 230
  • 1
  • 6
  • Your code example is a little off.. You don't call `function doThis($row->awesome);` but just `doThis($row->awesome);`. – Rihards Jun 24 '11 at 23:04
  • You are not doing any error checking on your query - it could crash due to an error in your SQL, but you would never see it. See [Reference: What is a perfect code sample using the mysql extension?](http://stackoverflow.com/q/6198104) for examples how to show errors – Pekka Jun 24 '11 at 23:05
  • @Richards. Thanks for the catch. The function calls fine... but the error is on the query. I've also added the "or die(mysql_error()) to the query. Let me edit. – LeGrande Jun 24 '11 at 23:07

1 Answers1

2

2 things: you haven't declared $db as a global variable within your function (so it's undeclared, causing the error you're seeing). Add the following:

global $db;

Second, remove the function keyword from inside your while loop. That's likely to cause php to biff.

gnxtech3
  • 782
  • 3
  • 7
  • the connection string is at the top of the page and referencing the variable $db. – LeGrande Jun 24 '11 at 23:08
  • Doesn't matter, the function cannot access default scoped variables, you have to global it for a function (outside of a class) to access a variable. – Nahydrin Jun 25 '11 at 00:18
  • good call. this worked beautifully. I've never had to do that before, but I suppose I've never had to build an import this large and complex, doing what it is doing. thanks for the help. – LeGrande Jun 25 '11 at 03:25