2

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.'/';
?>
1
  • Do you want to create a URL for every single id? Commented Feb 13, 2019 at 3:25

2 Answers 2

3

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.'/';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

I can confirm this worked for me. But had to set @fyrye as the answer. Thank you!

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.