Jump to content

How can I enter an array into a foreach loop and return it?


naike

Recommended Posts

Hi.

I'm making a registration form, that will put each entered item into $_POST, which will then submit to the same page.

First, I need to has the password with this method:

<?php
public function hash_password($password) {
	$result = hash(sha512, $password . SALT);
	return $result;
}
>?

then prepare the entered data for mysql with this method:

<?php
public function query_prep($value) {
$result = $this->real_escape_string($value);
	if (!$result) {
		die("Preparing query failed: " . $this->errno);
	}
return $result;
}
?>

 

However, how can I "validate" the form.

I need to pass the now prepared $_POST array into a loop, that executes the prepare method on each item in the array and then puts it in an array again.

Also, how could I do some kind of function that checks if all required fields were filled, and how I can fail the submission if invalid characters were used.

Link to comment
Share on other sites

Thanks guys.

It works, but something is wrong when I try to use it in this function:

<?php
    public function validate_registration($array) {
    $result = array_map($this->database->query_prep, $array);
        if (!$result){
        die("Form validation failed!"); }
        return $result;
}
?>

query_prep is here:

<?php
public function query_prep($value) {
$result = $this->real_escape_string($value);
	if (!$result) {
		die("Preparing query failed: " . $this->errno);
	}
return $result;
}
?>

Link to comment
Share on other sites

Ah I see, thanks!

However, now I face another problem.

After playing around with array_map, I noticed that it removes/doesn't recover it as an associative array.

So now I have a question.

 

After I'm done submitting the form, processed all the $_POST arrays information through real escape strings and password hashes, I then want to insert it into my database.

I originally though I'd just pass an associative array into my method:

<?php
public function create_user($array) {
$date = date('Y-m-d H:i:s');

$sql = "INSERT INTO users (username, first_name, ";
$sql .= "last_name, password, email, secret_question, ";
$sql .= "secret_answer, create_time) VALUES ";
$sql .= "('{$array['username']}', '{$array['first_name']}', '{$array['last_name']}', ";
$sql .= "'{$array['password']}', '{$array['email']}', '{$array['secret_question']}', '{$array['secret_answer']}', ";
$sql .= "'{$date}');";

$this->database->db_query($sql);
?>

However now I have one problem.

First, the array_map function converts my associative array into a normal array.

So if I use it, it would enter the wrong data into the wrong columns in my database.

Link to comment
Share on other sites

First, if you only pass 1 array to the callback then it shouldn't change the keys:

$a = array('username'=>'AbraCadaver','first_name'=>'Shawn');
print_r( array_map('mysql_real_escape_string', $a) );

Yields:

Array
(
    [username] => AbraCadaver
    [first_name] => Shawn
)

 

Second, if the form inputs are text (actually anything other than checkbox or radio) then they will be posted as an empty string and that's what will be inserted into the database.

Link to comment
Share on other sites

Thanks, yes I played around and tried to fake-enter some sql queries.

 

Anyway, I'm passing in an array into this method:

 

<?php
public function array_query_prep($array) {
$result = array_map($this->real_escape_string, $array);
	if (!$result) {
		die("Preparing query failed: " . $this->errno);
	}
return $result;
}
?>

 

However it doesn't perform the function $this->real_escape_string (my class extends mysqli).

I tried to enter usernames etc with '"\/ etc and checked my db and sure enough it was a chaos.

So what's wrong with that method?

Link to comment
Share on other sites

Thanks, yes I played around and tried to fake-enter some sql queries.

 

Anyway, I'm passing in an array into this method:

 

<?php
public function array_query_prep($array) {
$result = array_map($this->real_escape_string, $array);
	if (!$result) {
		die("Preparing query failed: " . $this->errno);
	}
return $result;
}
?>

 

However it doesn't perform the function $this->real_escape_string (my class extends mysqli).

I tried to enter usernames etc with '"\/ etc and checked my db and sure enough it was a chaos.

So what's wrong with that method?

 

$result = array_map( array($this, 'real_escape_string'), $array );

Link to comment
Share on other sites

Thanks, yes I played around and tried to fake-enter some sql queries.

 

Anyway, I'm passing in an array into this method:

 

<?php
public function array_query_prep($array) {
$result = array_map($this->real_escape_string, $array);
	if (!$result) {
		die("Preparing query failed: " . $this->errno);
	}
return $result;
}
?>

 

However it doesn't perform the function $this->real_escape_string (my class extends mysqli).

I tried to enter usernames etc with '"\/ etc and checked my db and sure enough it was a chaos.

So what's wrong with that method?

 

$result = array_map( array($this, 'real_escape_string'), $array );

Thanks once again!

Is there a logical explanation for putting $this->real_escape_string into an array?

Or is it just done like that.

Link to comment
Share on other sites

Thanks once again :P

And I have yet another problem:

<?php
public function array_query_prep($array) {
$result = array_map(array($this, 'real_escape_string'), $array);
	if (!$result) {
		die("Preparing query failed: " . $this->errno);
	}
return $result;
}
?>

It works fine and even if I print_r(); $result just before returning it, it prints the correct array with everything nice and done.

But when I then externally want to use the returned $result and insert it into my create user method, it inserts nothing, just emptiness.

Even if I print_r my returned array (from the index page where the form sends the data in) it prints out empty.

Link to comment
Share on other sites

PHP Parse error:  syntax error, unexpected T_PUBLIC in /htdocs/test.php on line 2

That file has nothing to do with the main page, I now removed it anyway.

But yeah I just went through my code and can't find an error.

Heres my code:

 

<?php
include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_database.php";
include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/values.php";

?>



<?php

class User {

    private $database;

    public    function __construct(MySqlDatabase $database) { //Type Hinting
    $this->database = $database;
}
    
    public function hash_password($password) {
        $result = hash(sha512, $password . SUOLA);
        return $result;
}
    
    public function find_all() {
    $result = $this->database->db_query("SELECT * FROM users");
    $final = mysqli_fetch_array($result);
    return $final;    
}
    
    public function find_by_id($id=1) {
    $result = $this->database->db_query("SELECT * FROM users WHERE id={$id}");
    $final = mysqli_fetch_array($result);
    return $final;    
}
    
    public function check_required($array) {
    if (empty($array['username']) || empty($array['first_name']) 
        || empty($array['last_name']) || empty($array['password'])
        || empty($array['email']) || empty($array['secret_question']) 
        || empty($array['password2']) || empty($array['secret_answer']) 
        || !($array['email'] === $array['email2'])
        || !($array['password'] === $array['password2'])) {
        die("Fill required fields!" . "<br />" 
            . "<a href='javascript:history.go(-1)'>Go back</a>");
        
        } else {
            $this->database->array_query_prep($array);
        }
    
    }
    
    public function create_user($array) {
    $date = date('d-m-Y H:i:s');
    
    $sql = "INSERT INTO users (username, first_name, ";
    $sql .= "last_name, password, email, secret_question, ";
    $sql .= "secret_answer, create_time) VALUES ";
    $sql .= "('{$array['username']}', '{$array['first_name']}', '{$array['last_name']}', ";
    $sql .= "'{$array['password']}', '{$array['email']}', '{$array['secret_question']}', '{$array['secret_answer']}', ";
    $sql .= "'{$date}');";
    
    $this->database->db_query($sql);
    }
}
?>

<?php
include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/values.php";
include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_user.php";
?>

<?php
class MySqlDatabase extends MySQLi {
    
    function __construct() {
        //Check if constants are missing
        if (!defined("DB_USERNAME") || !defined("DB_SERVER") || 
            !defined("DB_PASSWORD") || !defined("DB_NAME")) {
            die("One or more of the database constants are missing!");
            }
            
        //Establish connection if constants are present using the parent class
        parent::__construct(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
        
        //Echo error message if connection has failed
        if ($this->connect_errno) {
            die("Database connection has failed: " . $this->connect_errno);
            }    
    }

    public function db_query($sql) {
    $result = $this->query($sql);
        if (!$result) {
            die("Database query failed: " . $this->errno);
        }
}

    public function array_query_prep($array) {
    $result = array_map(array($this, 'real_escape_string'), $array);
        if (!$result) {
            die("Preparing query failed: " . $this->errno);
        }
    return $result;
} 
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="../stylesheets/main.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body class="main_body">
<div id="container">
<div id="header">
    <div id="top">
      <div id="login">
        <form action="" method="post" target="/login/">
          <label for="username">Username:</label><br />
          <input name="username" type="text" class="text" maxlength="20" /><br />
        <label for="password">Password:</label><br />
        <input name="password" type="password" class="text" maxlength="30" /><br />
        <input name="submit" type="submit" class="loginbtn" value="Login" /></form>
      </div>
    </div>
<div>
  <h1>Welcome to _________ website!</h1>
</div>

<?php
include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/values.php";
include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/functions.php";
include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_database.php";
include_once $_SERVER['DOCUMENT_ROOT'] . "/includes/class_user.php";
?>
<?php

$database = new MySqlDatabase();
$user = new User($database);




if (isset($_POST['submit'])) {
    $result = $user->check_required($_POST); //this is where I get nothing back
    $user->create_user($result);
    die("Registration was successful!");
    } else {
    $username = "";
    $first_name = "";
    $last_name = "";
    $password = "";
    $email = "";
    $email2 = "";
    $secret_question = "";
    $secret_answer = "";
    unset($_POST);
    }


    
?>
<form action="" method="post" target="_self">
Username: <input type="text" name="username" class="text" maxlength="20" value="<?php echo htmlentities($username); ?>" /><br />
First Name: <input type="text" name="first_name" class="text" maxlength="20" value="<?php echo htmlentities($first_name); ?>" /><br />
Last Name: <input type="text" name="last_name" class="text" maxlength="20" value="<?php echo htmlentities($last_name); ?>" /><br />
Password: <input type="password" name="password" class="text" maxlength="30" value="<?php echo htmlentities($password); ?>" /><br />
Enter again: Password: <input type="password" name="password2" class="text" maxlength="30" value="<?php echo htmlentities($password2); ?>" /><br />
Email: <input type="text" name="email" class="text" maxlength="30" value="<?php echo htmlentities($email); ?>" /><br />
Enter again: Email: <input type="text" name="email2" class="text" maxlength="30" value="<?php echo htmlentities($email2); ?>" /><br />
Secret Question: <input type="text" name="secret_question" class="text" maxlength="35" value="<?php echo htmlentities($secret_question); ?>" /><br />
Secret Answer: <input type="text" name="secret_answer" class="text" maxlength="35" value="<?php echo htmlentities($secret_answer); ?>" /><br />
<input type="submit" name="submit" class="submitbtn" value="Submit" />
<?php




?>
</div>
</div>
</body>
</html>

Link to comment
Share on other sites

Judging by the <?php ?> tags in that code block, I thought you had isolated it to its own file for testing.

What do you mean?

I've done some testing.

And my conclusion is that array_query_prep doesn't return an array. Even though it is an array, but after using return it just disappears into nothing.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.