0

In php, when we write and execute a query, we use while loop to iterate

$sql  = "SELECT username, role FROM studentlogin WHERE username = '$username' and password = '$password'";
        $res = mysql_query($sql);

            while($row = mysql_fetch_array($res, MYSQL_NUM)){
                   $uname = $row[0];
                   $stud_role = $row[1];
            }

We then use variables $uname and $stud_role somewhere in our code. I'm trying to do something similar in codeigniter but it fails.

function studentlogin($username, $password)
    {

        $query = "SELECT username, role FROM studentlogin WHERE username = ? and password = ?";
        $result = $this->db->query($query, array($username, $password));

        if($result->num_rows() == 1)
        {               
            return $result;
        }

        else
        {
            return false;
        }
    }

I'm calling this function from controller as follows

$data['info'] = $this->student_model->stdentlogin($username, $password);

Here comes the problem. I've tried using the same while loop as above, but it doesn't work here. How can i access each of the two values separately in controller? Need some help.

2 Answers 2

1

Instead of returning $result, return $result->row_array();

This will return a named hash of the columns you grabbed. It will be a single element array, so you won't need to loop through it.

For more information on grabbing database data in codeigniter, check out the database class information.

Sign up to request clarification or add additional context in comments.

Comments

0

while() evaluates an expression as it processes a loop. If the expression evaluates to TRUE, the loop continues. If it is FALSE, it stops. Not really the best place for this. (Btw, mysql_* functions are deprecated in PHP as of now, so I'd really suggest ignoring how they work).

The CI Database user guide has lots of handy examples and information about how to retrieve data from your DB. In your case, if you are retrieving a single row, you should use $result->row() or $result->row_array(), the former will return a stdClass object, the latter an associative array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.