Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

For those that don't want to read the very detailed and specific information the basic question in it's simplest form is this:

  • How do you take a multi-dimensional array from an SQL query and convert it to something stripped down and simple with just the value information such as this: array(1,2,3,4,5,6,7,8,9)

How do I go about creating a simple 1 dimensional array of say employee id's from an SQL query in PHP?

This is more for my understanding than it is for live code. I have been playing around with php and MySQL and my brain came up with what I feel like is a logical idea to try. I am going to break this down as I am in my head so you understand where I am coming from.

Goal: To allow an employee to log into private section of website

Logical Reasoning:

  • 1.) Create script to connect to DB (Done)
  • 2.) Check to see if external I.P. matches the business I.P. or is different? Static I.P. assumed (Done)
  • 3.) If I.P. matches, proceed to dynamically create a drop down of employee names to choose from with the "emp_id" stored as the value then passed through with GET (Done)
  • 4.) If I.P. does NOT match, present login form. Once validated, set $ip to be equal to business I.P. and proceed to drop down list (Done)
  • 5.) Once name is selected, proceed to main page of employee area. (Done)
  • 6.) Validate that employee truly exists and make sure that URL has not been tampered with (Problem)

Now I realize this is not the safest or best route to take, but I want to understand why my reasoning is not working. The reason I would want this to validate is so that the employee list would be dynamic, and an old employee couldn't just type in there id in the user="emp_id" part of the url and gain access. This could happen if a hard coded array was used to store emp_id instead of grabbing one from database. So to validate that the employee exists, I chose to go with what logically made sense in my mind at the time.

Route I took:

<?php
include('inc/dbConnect.php');

//Store user id aka emp_id to variable from URL 
$user = $_GET['user'];
$key = $_GET['key'];

//Grab data from database, create array, and step through storing emp_id values to said array.
$result = mysqli_query($dbconnect, 'SELECT emp_id FROM employee');
$data = mysqli_fetch_array($result);
$usercheck = array();
while($data = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $usercheck[] =  $data['emp_id'];

    //Debugging only to see what array looks like
    print_r($usercheck);
    }

//Validate that employee id exists in generated array from database. If not boot them off immediately.
if(!in_array($user, $usercheck) || $key != 'Not Important'){
    echo "<meta http-equiv=\"refresh\" content=\"0;url=index.php\">";
} else {
    // I did this so even if someone where to input wrong data, it wouldn't flash the html to them, or allow them to stop the page from loading as it flashed to see data etc. Plus I hate having to echo out html for a page bleh.
    include('html content file here');
    }
?>

As you can see, I am grabbing the user id and the key from the URL passed from the previous form. The key is unimportant at this point. I am focused on the dynamic element of the user id.

So I create an array from the emp_id from the MySQL database and want to use that array to check against the variable stored in $user. Upon researching online many suggested using in_array(). So I gave it a go. Now of course this works great except if you select the very first entry on the dynamic drop down list. If you select that, it will boot you back to the index page to log in again. Other than that, any other employee logs in, the url must stay the way it is or it boots you off the system.

I am wanting my array to be something simple, like this: $usercheck = array(1,2,3,4,5,6,7,8,9);

This would make it very easy to check against the value of the user id. However, I see that the array is much more complicated then this when actually created by my script. It looks like this: Array from MySQL Database I have looked and looked and looked at how to get this array stored as something simple with just the values of emp_id stored and nothing more. I don't need the keys, I don't need anything extra except my emp_id stored as a very simple array to be used to validate the user id passed from the previous form.

I am aware that this is probably something stupid simple that I am missing and just not grasping but i have taken a step back, thought about it and tried numerous other methods and can't get it to work as intended. So what is wrong with my logic here? I get my code is wrong because it doesn't work but why is this more difficult than it appears initially given that it is such a seemingly simple thing to do in my mind to return an array of only the values and nothing else.

Before any hates on this and telling me that there are better ways to do this, this code sucks, it's not secure, etc I know this. This is all hypothetical and I am running the code on a development server here at work just messing with it on my lunches trying to see what I am missing.

P.S. This is for those that want to see how I am creating the dynamic drop down:

echo '<form class="form-horizontal" action="main.php" method="GET">';
            echo '<div class="form-group">';
            echo '<label for="user" class="control-label col-xs-4 col-md-3">Username</label>';
            echo '<div class="col-xs-8 col-md-3">';
            echo '<select name="user" class="form-control">';
            echo '<option value="1">Select Name</option>';
            $result = mysqli_query($dbconnect, 'SELECT emp_id, emp_name FROM employee ORDER BY emp_name');
            if($result) { 
                while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                    echo '<option value="' . $row['emp_id'] . '">' . $row['emp_name'] . '</option>';
                    } 
                } else {
                    mysqli_connect_error();
                }
            echo '</select>';
            echo '</div>';
            echo '</div>';

            echo '<label for="submit" class="control-label col-xs-4 col-md-3"></label>';
            echo '<div class="col-xs-8 col-md-3">';
            echo '<input type="submit" value="Log In" style="margin-bottom: 100px;"/>';
            echo '</div>';
            echo'</form>';
share|improve this question
    
Did you found a solotion? – Jorge Mejia Apr 8 '16 at 17:29
    
not yet, i got pulled away from my desk and haven't had a chance to try to object oriented version yet. Is there a procedural version that would work? – PBSWebDesign Apr 8 '16 at 19:53

If I understood your question correctly, you want an array of all the user ID's.

if you're worried about scopes inside loops, you actually do not need to do this since the array is already an enumerate of your data.

// TODO: Complete the query
$data = $conn->query("SELECT [...]");

Your data should look something like this:

$data = Array (
    0 => 1,
    1 => 2,
    2 => 3
)

Since its built inside that format anyway

But you could do this which would be a lot better structured for a login:

class Employee
{
    private $Eid;
    private $Key;

    public function __construct($key,$eid)
    {
        $this->Eid = $eid;
        $this->Key = $key;
        self::login();
    }

    public function login()
    {
        // TODO: Strip your html out of your derived inputs
        require_once 'database.php';
        foreach ( $db->query("SELECT * FROM tbl WHERE emp_id = '$this->Eid'" as $row );
        {
            // TODO: Add a authenticate column (ie: 3 is admin)
            if ( $row['admin'] == 3 )? "success" : "fail"; // change to what you like
        }
    }
}

It can be used like:

if(isset($_GET['key']) && isset($_GET['eid']))? (new Employee($_GET['key'], $_GET['eid']))->Login() : "No Key or Eid given!";
share|improve this answer

Try this:

In your example your array is only saving one value because you are not indexing it, if you create a counter, you can index your array, like in this example.

$count = 0;
while($data = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $usercheck[$count] =  $data['emp_id'];

    //Debugging only to see what array looks like
    print_r($usercheck);
     $count ++;
}
share|improve this answer
    
I tried this, unfortunately it made no difference. The first employee into the system still gets booted every time, no matter what there id number is. – PBSWebDesign Apr 8 '16 at 15:33
    
Why should the OP "try this"? A good answer will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO. – Jay Blanchard Apr 8 '16 at 15:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.