sidegeeks
sidegeeks

Reputation: 1041

How to make SQLite3 fetched array more clean?

I'm using SQLite3 for a web app of mine. Everything works fine. I'm able to access the db, create and everything.

But.. when I retrieve the information using the below code:

function db_select($username, $password, $database = 'Railway') {

$db = db_connect($database);

$result = $db->query("SELECT * FROM users ") or die('Query failed');
$rowss = array();

while ($row = $result->fetchArray()) {
    $rowss[] = $row;
}

print_r($rowss);
}

OUTPUT

Array ( 
[0] => Array ( [0] => John123 [username] => John123 
[1] => foo [password] => foo 
[2] => John [fname] => John 
[3] => Smith [lname] => Smith 
[4] => 21 [age] => 21 
[5] => [email protected] [email] => [email protected] 
[6] => Male [sex] => Male ) )

This array doesn't make sense, how would one individually retrieve the information like fname, lname, age, username, etc?

Is there a way I can convert this into the following form?

Array (
username => John123,
password => foo,
fname => John
lname => Smith
)

Upvotes: 0

Views: 4321

Answers (2)

sidegeeks
sidegeeks

Reputation: 1041

Found this answer from the PHP docs.

$row = array(); 

    $i = 0; 

     while($res = $result->fetchArray(SQLITE3_ASSOC)){ 

         if(!isset($res['username'])) continue; 

          $row[$i]['username'] = $res['username']; 
          $row[$i]['fname'] = $res['fname']; 
          $row[$i]['lname'] = $res['lname']; 
          $row[$i]['age'] = $res['age']; 
          $row[$i]['email'] = $res['email']; 
          $row[$i]['sex'] = $res['sex']; 
          $row[$i]['phone'] = $res['phone']; 
          $i++; 

      } 


print_r($row);

Outputs this beautiful array.

Array ( 
[0] => Array ( 
[username] => John123 
[fname] => John 
[lname] => Smith 
[age] => 21 
[email] => [email protected] 
[sex] => Male 
) 

Upvotes: 1

Maarten van Middelaar
Maarten van Middelaar

Reputation: 1721

Try

$result->fetchArray(SQLITE3_ASSOC)

Since you do not seem to be interested in the column number.

Upvotes: 5

Related Questions