Jump to content

Method doesn't return an array, it returns nothing.


naike

Recommended Posts

I've done pretty much everything I can come up with.

The method itself works fine, if I print_r(); just before returning it, it successfully returns the array.

But once returned, it's empty.

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) { // this method gets called first
    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); // it then continues to the next method automatically
        }
    
    }
    
    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) { // continues to this method
    $result = array_map(array($this, 'real_escape_string'), $array);
        if (!$result) {
            die("Preparing query failed: " . $this->errno);
        }
// if i print_r here, it returns the array as it should
    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>

 

Any ideas?

Link to comment
Share on other sites

You haven't stated which method or any other clues to what is not working, but I see several problems:

 

public function db_query($sql) {
// i don't see a query() method in your code
        $result = $this->query($sql);
        if (!$result) {
            die("Database query failed: " . $this->errno);
        }
// you need to return the result or assign it as an object var
        return $result;
}

 

This method currently only returns one row.  Try this:

 

public function find_all() {
    $result = $this->database->db_query("SELECT * FROM users");
// need to fetch all rows and put them in an array
    while($row = mysqli_fetch_array($result)) {
       $final[] = $row;
    }
    return $final;    
}

Link to comment
Share on other sites

You haven't stated which method or any other clues to what is not working, but I see several problems:

 

public function db_query($sql) {
// i don't see a query() method in your code
        $result = $this->query($sql);
        if (!$result) {
            die("Database query failed: " . $this->errno);
        }
// you need to return the result or assign it as an object var
        return $result;
}

 

This method currently only returns one row.  Try this:

 

public function find_all() {
    $result = $this->database->db_query("SELECT * FROM users");
// need to fetch all rows and put them in an array
    while($row = mysqli_fetch_array($result)) {
       $final[] = $row;
    }
    return $final;    
}

Well array_query_prep isn't returning anything, whats wrong?

Link to comment
Share on other sites

if your code is still the same, you don't ask for it to return anything. You just call it without defining a variable to hold the result:

 

$this->database->array_query_prep($array);

What do you mean?

I'm doing this in this line:

    $result = $user->check_required($_POST);

    $user->create_user($result);

 

Also if you were talking about the method check_required, this method does pass the array to the final method, array_query_prep, this one also successfully processes the array, but it doesnt return it, and I don't get why.

Even if I print_r just before returning the array, it works fine, but after returning, its gone.

Link to comment
Share on other sites

if you want to use the result returned from a function, you need to assign a variable to hold it:

 

$result_array = $this->database->array_query_prep($array);

Aah it works now, thank you!

Anyhow.

Just asking since no tutorials cover this.

Should I do this with php or javascript:

Basically I have a registration form, and I want to give somekind of feedback if you enter the wrong info.

Not just "correct your mistakes", but also tell, what was wrong with the form.

 

Should I just use javascript and say let a popup do the work, or should I got with a php approach on this one?

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.