0

I am trying to make a function that gets the name of a user from their user id. The function needs to search a database for the matching id. However, when I try the function i get the following error:

Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in M:\xampp\htdocs\includes\main.php on line 41

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in M:\xampp\htdocs\includes\main.php on line 45

Warning: mysqli_error() expects exactly 1 parameter, 0 given in M:\xampp\htdocs\includes\main.php on line 45
Error Getting Author Name:

The Code For The Function:

function GetAuthorNameFunction($FunctionAuthorID) 
{
$FunctionAuthorID = strip_tags($FunctionAuthorID);
$FunctionAuthorID = mysqli_real_escape_string($myConnection,$FunctionAuthorID); //Line 41
		
//Get Author Name//		
$sqlCommand = "SELECT * FROM users WHERE ID='$FunctionAuthorID' LIMIT 1";
$query = mysqli_query($myConnection, $sqlCommand) or die("Error Getting Author Name: " . mysqli_error());// Line 45
		while ($row = mysqli_fetch_array($query)) { 
			$FunctionAuthorName = $row["Name"];
		} 
		mysqli_free_result($query);

//Return Value//		
return $FunctionAuthorName;
}

The code that calls the function is in another page:

$NewsAuthorName = GetAuthorNameFunction($NewsAuthID);

The database connection code is in the same file at the top.

$db_host = "localhost";
$db_username = "user"; 
$db_pass = "password"; 
$db_name = "database";
 
$myConnection = mysqli_connect("$db_host","$db_username","$db_pass", "$db_name") or die ("could not connect to mysql");

The sql query works when its not in the function. Also, i tried echoing out $FunctionAuthorID and it gave the right number and i tried echoing the sql query and that looked fine. All i can think of is it is something to do with the connecting but i don't know what.

Any help would be much appreciated. Thanks.

Edited by Monster Killer: n/a

1
Contributor
3
Replies
6
Views
7 Years
Discussion Span
Last Post by Monster Killer
0

Hmm. It seems to work if I completely re-define the connection inside the function. Is this a normal thing to have to do? Is there a better way round it?

0

I am having to put a new connection string in every function that uses MySQLI. There must be a better way.

0

SOLVED: It might not be the best of solutions but i created a separate function to connect to mysql and call it for each connection. it works fine now.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.