Jump to content

[SOLVED] Function not working


Danny620

Recommended Posts

I am programming a function named val() and when i pass val($username) it is should valiadate what the user has but in texbox. but the problem is when i try to mysqli_real_escape_string($dbc,$username); it says Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\val.php on line 19 but i have given it the database connection $dbc here is the code.

 

<?php 

require_once('access/mysqli_connect.php');

//Function val validates form submissions by;
//Striping html tags from from;
//Must be greater than three letters long;

function val($field = false){

$errors = false;

		if(strlen($field) > 3){

		strip_tags($field);
		$username = $field;

		$username = mysqli_real_escape_string($dbc,$username);

		} else {

		$errors = "Field must be greater than three letters long!";

		}

		if($errors){

	echo $errors; }

		}

	//END of val function;
?>

theres the val() function code and here is my db connect

 

<?php # Script 16.4 - mysqli_connect.php

// This file contains the database access information. 
// This file also establishes a connection to MySQL 
// and selects the database.

// Set the database access information as constants:
DEFINE ('DB_USER', '*********l');
DEFINE ('DB_PASSWORD', '*********');
DEFINE ('DB_HOST', '*********');
DEFINE ('DB_NAME', '*********');

// Make the connection:
$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

if (!$dbc) {
trigger_error ('Could not connect to MySQL: ' . mysqli_connect_error() );
}

?>

and then my form that needs to be valiadated

 

<?php include('val.php');?>
<?php 
	if(isset($_POST['sub']))	{
	$user = $_POST['username'];
    echo val($user);
				}
?>
<form name="form1" method="post" action="">
  <label>
  <input name="username" type="text" id="username" value="<?php echo $username; ?>">
  </label>
  <p>
    <input name="sub" type="hidden" id="sub" value="TRUE">
  </p>
  <p>
    <label>
    <input type="submit" name="send" id="send" value="send">
    </label>
</p>
</form>

Link to comment
https://forums.phpfreaks.com/topic/165719-solved-function-not-working/
Share on other sites

It is because the variable $dbc cannot be seen by your function. This is due to functions having their own variable scope.

 

A dirty fix is to change

function val($field = false){
   
   $errors = false;

 

to

function val($field = false){
    global $dbc;
   
   $errors = false;

 

Now your function will work as expected

 

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.