PHP mysql_query error
I'm trying to learn and I'm stuck. I don't understand why this doesn't work. If I just leave the include and remove the function call and don't wrap the database connection in a function it works properly.
What is it that I'm missing here?
Error Message:
Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home3/badamsne/public_html/views/dogs.php on line 24 Database query failed:
Web page code:
<?php
include("../model/db_conn.php");
db_conn();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
// 3. Perform database query
$result = mysql_query("SELECT * FROM dogs", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
// 4. Use returned data
while ($row = m开发者_如何学JAVAysql_fetch_array($result)) {
echo $row[0]." ".$row[1]."<br />";
}
?>
</body>
</html>
<?php
// 5. Close connection
mysql_close($connection);
?>
PHP Function in separate file:
<?php
function db_conn() {
// 1. Create database connection
$connection = mysql_connect("localhost","website_admin","p@ssw0rd");
if(!$connection) {
die("Database connection failed: " . mysql_error());
}
// 2. Select a database to use
$db_select = mysql_select_db("website_db", $connection);
if(!$db_select) {
die("Database selection failed: " . mysql_error());
}
}
?>
Thanks! Tom
you never return $connection from your function, nor do you capture it as a variable in the top file.
Change this:
<?php
include("../model/db_conn.php");
db_conn();
?>
To This:
<?php
include("../model/db_conn.php");
$connection = db_conn();
?>
And add
return $connection;
to your function.
Your problem here is, that the $connection variable isn't global. Which means it's only "visible" in the context of function db_conn() and not in the main program.
There are three simple solutions to your problem:
- Add 'global $connection;' as the first command to your function.
- You don't have to provide the MySQL connection resource to the mysql_query function if you've just opened one connection. So 'mysql_query( "SELECT * FROM dogs" );' would work too.
- You could also return the $connection variable from your function.
It looks like $connection
is created as a local variable to the db_conn()
function. You could declare it global so that other code has access to it:
function db_conn()
{
global $connection;
$connection = mysql_connect( ... );
}
// now $connection is available everywhere
note: Most programming languages have caveats regarding misusing global variables. See Global Variables Considered Harmful by W.A. Wulf and M. Shaw (ACM SIGPLAN, 1973).
精彩评论