views:

33

answers:

2

Hey,

I'm using the code:

function insertV($deptx, $coursex, $secx, $isbnx,$titlex, $authorx,$usedpx,$newpx)
{
$sql = "INSERT INTO `$deptx` (`course`, `sec`, `isbn`, `title`, `author`, `usedp`, `newp`) 
VALUES ('$coursex','$secx','$isbnx','$titlex','$authorx','$usedpx','$newpx')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }

}

$dept = "ACCOUNTG";
$course = "340";
$sec = "101";
$isbn = "9780324651140";
$title = "FINANCIAL ACCOUNTING";
$author = "STICKNEY";
$usedp = "$129.75";
$newp = "$199.75";
insertV($dept,$course,$sec,$isbn,$title,$author,$usedp,$newp);

But I keep getting an error:

Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/public_html/mysite.com/myscript.php on line 14 Error:

I'm guessing it has to do with me trying to access a table using a var?

Any help would be appreciated, I'm still new to PHP if you couldn't tell :P

Thanks!

EDIT: Oh yeah, line 14 is

if (!mysql_query($sql,$con))
+1  A: 

You aren't defining your $con within the function. This is part of PHP's scoping rules. Variables defined outside a function are not visible within a function unless you declare them global, you'd need something like this:

function insertV(...) {
    global $con;

    $query = "...";
    etc...
}

So, the error is due to $con being null within the function, which is "not a valid MySQL-link resource"

Marc B
Ahhhhh, that makes sense. Thanks!
Sally
+5  A: 

The error means that the connection you're providing to mysql_query ($con) is not a valid MySQL resource. $con is never defined in your function anywhere. You want to open a connection before querying, like so:

$con = mysql_connect("[mysql server hostname]", "[mysql username]", "[mysql password]");

If you have already created a connection to your MySQL server outside of the function, you can import the global $con variable by adding global $con; at the top of your function (see variable scope in the php docs if you'd like some more information).

Alternately, the connection resource is an optional parameter in all the mysql functions, so you can just use mysql_query(...) (without specifying the connection), and PHP will use the last connection opened by mysql_connect.

Daniel Vandersluis
+1 for connection being an optional parameter in mysql_query()
Mark Baker