haZh
haZh

Reputation: 127

PHP Implode Value

How can I get a single value from the array below? The current result for the 19th row is like 19 repeated twice as;

E:/database/users/1919/

I just need the 19, so the URL will look like;

E:/database/users/19/

<?php
$db = new SQLite3('C:/inetpub/wwwroot/database.db');
$row = $db->query('select id from users');
while ($lastrow = $row->fetchArray())
{
$id = implode($lastrow);
}
$database = 'E:/database/users/'.$id.'/';
?>

Upvotes: 2

Views: 138

Answers (2)

Will B.
Will B.

Reputation: 18416

SQLite3Result::fetchArray by default uses the SQLITE3_BOTH mode, which returns a 0-indexed and associative array of the selected columns.

Meaning you will receive a value like:

$lastrow = array(
   0 => '19',
   'id' => '19'
);

To resolve the issue you simply need to change fetchArray to retrieve a single value using either SQLITE3_NUM or SQLITE3_ASSOC.

$row = $db->query('select id from users');
while ($lastrow = $row->fetchArray(SQLITE3_NUM)) {
    $id = implode($lastrow);
    //list($id) = $lastrow; //alternative to implode
}
$database = 'E:/database/users/'.$id.'/';

Alternatively you only need to specify the column name to retrieve, instead of using implode.

$row = $db->query('select id from users');
while ($lastrow = $row->fetchArray()) {
    $id = $lastrow['id'];
}
$database = 'E:/database/users/'.$id.'/';

Since it appears you only need the last row, I recommend changing your query to improve overall performance.

SELECT MAX(id) FROM users 

or

SELECT id FROM users ORDER BY id DESC LIMIT 1 

Allowing you to retrieve the last id without iterating over the entire users table.

if ($row = $db->query('SELECT MAX(id) FROM users')) {
    if ($row->numColumns()) {
        list($id) = $row->fetchArray(SQLITE3_NUM);
        $database = 'E:/database/users/'.$id.'/';
    }
}

Upvotes: 3

Roshan
Roshan

Reputation: 842

Since the value of $lastrow is array which is correct, and you said that it gets the value twice, you may try this, declare $id = array() and try to re assign value to $id = array_shift($lastrow) then another variable that will handle the value like $implodedArray = implode($id) and set to your like $database = 'E:/database/users/'.$implodedArray .'/'; this should be getting the value 19. This is an idea to manipulate your array.

Upvotes: 2

Related Questions