Jump to content

Problems with function and mysqli_real_escape_string


pioneerx01

Recommended Posts

I am starting to work with MySQLi and so far so good. I am having issues with mysqli_real_escape_string in function.

	if(!function_exists('todatabase'))
	{
		function todatabase ($variable)
		{
			$variable = mysqli_real_escape_string($variable);
			return $variable;
		}
	}

Every time I put something into database I run it through "todatabase" function, but if I have mysqli_real_escape_string in there the function does not execute. I also get no error messages and rest of the code runs to the end smooothly. I tried using:

 

$variable mysqli_real_escape_string($dbc, $variable);

$variable = $dbc->real_escape_string($variable);

 

But it did not work either. What am I missing?

mysqli_real_escape_string requires the database object as a first parameter. Can you show the code which defines $dbc? Also what do you mean by "the function doesnt execute"? What is the input variable and what are you expecting to be returned?

The connect code is

	DEFINE ('DBNAME', '');
	DEFINE ('DBUSER', '');
	DEFINE ('DBHOST', '');
	DEFINE ('DBPW', '');
	
	$dbc = mysqli_connect(DBHOST,DBUSER,DBPW,DBNAME);
	
	if (mysqli_connect_errno($con))
	{
		echo "Could not connect to the database. <br/>";
		exit();
		die();
	}
	
	else
	{
		mysqli_set_charset($dbc, "utf8");
	}

When I do this

$dbc->query("UPDATE table SET `first_name` = '".todatabase($first_name)."' WHERE ID = '#' ");

first_name remains the same and does not change, no errors though. (errors are not supressed)

you need to pass the $dbc variable into the function as a call time parameter.

 

you also need to turn on php's error_reporting/display_errors to get php to help you. you would be getting several php error's when you tried to use $dbc inside the function.

 

lastly, for a user written function, there's no good reason to test if it doesn't exist before defining it. that's just more lines of code to clutter up what you are doing.

Oh yes, I could do just that. Why did't I think of that:

 

    function todatabase ($dbc, $variable)
    {
        $variable = preg_replace('/\s+/', ' ', $variable);
        $variable = mysqli_real_escape_string($dbc, $variable);
        return $variable;
    }
 

 

$dbc->query("UPDATE table SET `first_name` = '".todatabase($dbc, $first_name)."' WHERE ID = '#' ");

 

Thank you all.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.