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 = mysql_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