Reputation: 41
I'm trying to get a basic registration page to work that's connected to a local database.
Notice: Undefined variable: dbhost in C:\wamp\www\functions.php on line 19
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\wamp\www\functions.php on line 19
Notice: Undefined variable: con in C:\wamp\www\functions.php on line 19
Warning: mysqli_error() expects parameter 1 to be mysqli, null given in C:\wamp\www\functions.php on line 19
These are the errors I get. They occur when I reference a function in my functions.php script.
<?php //functions.php
$dbhost = 'localhost'; //change to webserver ip
$dbname = 'maindb';
$dbuser = 'administrator';
$dbpass = 'password';
$appname = "webapp";
$con = mysqli_connect($dbhost,$dbuser,$dbpass) or die (mysqli_error($con));
mysqli_select_db($con, $dbname) or die (mysqli_error($con));
function createTable($name, $query)
{
queryMysql("CREATE TABLE IF NOT EXISTS $name($query)");
echo "Table '$name' created or already exists<br>";
}
function queryMysql($query)
{
$result = mysqli_query($dbhost, $query) or die(mysqli_error($con));
return $result;
}
I'm not exactly sure as to what the issue here is. I learned PHP a few years ago, and it seems quite a bit has changed since 2011. Any help would be appreciated.
Upvotes: 2
Views: 974
Reputation: 78994
mysqli_query
needs the connection not the host and you have to pass it in:
function queryMysql($con, $query)
{
$result = mysqli_query($con, $query) or die(mysqli_error($con));
return $result;
}
Then when you call it:
$result = queryMysql($con, $query)
Upvotes: 1
Reputation: 219804
Those variables were declared in the global scope and therefore are not available to your functions. To make them so you need to pass them as parameters of that function:
function queryMysql($query, $con, $dbhost)
(You can also use the global
keyword but that is a bad practic so I won't show it here).
Also, the first parameter of mysqli_query()
should be your MySQL connection resource which is stored in $con
, not$dbhost
function queryMysql($query, $con)
{
$result = mysqli_query($con, $query) or die(mysqli_error($con));
return $result;
}
Upvotes: 4