Friday, May 13, 2016

Fetch the next set of MySQL records in PHP (LIMIT offset,count) — correct & secure approach

Greetings Of The Day!

While we were working with web services using PHP and MySQL for an Android application, we had a use case to retrieve and show a set of data to one user and the remaining set of data to another user based on the login details.

Application had Master and Partner users. Consider we have around 25 records in the abc MySQL table. Now I have to fetch and show first 12 data to Master and the remaining 13 data to the partner.

For the above use case we had to write the web-services. I am not going to discuss about the web services here but the MySQL query we used to get such data was very important here that we are going to discuss.

Key concepts

  • Use LIMIT to restrict how many rows MySQL returns.
  • LIMIT accepts either a single value (LIMIT count) or two values (LIMIT offset, count). offset is zero-based.
  • Always use ORDER BY when splitting or paginating, otherwise the order of rows is nondeterministic.
  • Use COUNT(*) to get the total rows instead of fetching all rows into PHP and counting them.

Original code (verbatim from the post)

These are the original code examples as they appeared in the post:

$result_row = mysql_query("SELECT * FROM abc where uid='$uid' ");

$totalrows=intval(mysql_num_rows($result_row)/2);
$result = mysql_query("SELECT * FROM abc where uid='$uid' 
LIMIT $totalrows") 
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
//Get the data
....
}
  $result_row = mysql_query("SELECT * FROM abc where uid='$uid' ");
  $totalrows=mysql_num_rows($result_row);
  $startindex=intval($totalrows/2);
$result = mysql_query("SELECT * FROM abc where uid='$uid'
LIMIT $startindex,$totalrows") 
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
//Get the data
....
}

Problems in the original examples (what to fix)

  1. Deprecated API: the examples use the old mysql_* extension which is removed in modern PHP. Use mysqli or PDO with prepared statements.
  2. Security: variables are interpolated into SQL directly ('$uid') — this allows SQL injection. Use parameterized queries.
  3. Wrong LIMIT usage in the partner query: LIMIT $startindex,$totalrows is incorrect because the second parameter is the number of rows to return, not the final index. If $totalrows is the total number of rows, you should use LIMIT $startindex, $totalrows - $startindex.
  4. No ORDER BY: without ORDER BY the split is nondeterministic.
  5. Inefficient counting: the code first selects all rows then counts them in PHP. Use SELECT COUNT(*) for the row count.

Correct approach (step-by-step)

  1. Get total rows using COUNT(*):
SELECT COUNT(*) AS total FROM abc WHERE uid = ?
  1. Compute split indices in PHP (example: split into two halves):
  • $total = (int) fetched total
  • $startIndex = intdiv($total, 2); // number of rows in the first half
  • $remaining = $total - $startIndex;
  1. Fetch the first half (Master) with ORDER BY and LIMIT:
SELECT * FROM abc WHERE uid = ? ORDER BY id ASC LIMIT ?

(Here LIMIT ? returns up to ? rows starting from offset 0.)

  1. Fetch the second half (Partner) with correct LIMIT offset,count:
SELECT * FROM abc WHERE uid = ? ORDER BY id ASC LIMIT ?, ?

(offset = $startIndex, count = $remaining)

Secure PHP examples

Below are two recommended secure implementations. The first uses mysqli (procedural style). The second uses PDO.

mysqli (procedural) example

// assume $mysqli is a connected mysqli object and $uid is from a trusted source
// 1) count rows
$stmt = mysqli_prepare($mysqli, "SELECT COUNT(*) FROM abc WHERE uid = ?");
mysqli_stmt_bind_param($stmt, 's', $uid);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $total);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);

$total = (int)$total;
$startIndex = intdiv($total, 2); // first half size
$remaining = $total - $startIndex;

// 2) fetch master (first half)
$stmt = mysqli_prepare($mysqli, "SELECT * FROM abc WHERE uid = ? ORDER BY id ASC LIMIT ?");
// bind_param requires types; 'i' for integer limit
mysqli_stmt_bind_param($stmt, 'si', $uid, $startIndex);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
    // process master rows
}
mysqli_stmt_close($stmt);

// 3) fetch partner (remaining rows)
$stmt = mysqli_prepare($mysqli, "SELECT * FROM abc WHERE uid = ? ORDER BY id ASC LIMIT ?, ?");
mysqli_stmt_bind_param($stmt, 'sii', $uid, $startIndex, $remaining);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
    // process partner rows
}
mysqli_stmt_close($stmt);

Note: Some older MySQL drivers do not allow binding LIMIT parameters as placeholders. If your driver does not allow it, cast and escape integers explicitly or build the LIMIT clause using integers only after careful validation (never interpolate user strings).

PDO example

// assume $pdo is a PDO instance connected to your DB
// 1) count
$stmt = $pdo->prepare('SELECT COUNT(*) FROM abc WHERE uid = ?');
$stmt->execute([$uid]);
$total = (int)$stmt->fetchColumn();

$startIndex = intdiv($total, 2);
$remaining = $total - $startIndex;

// 2) fetch master (first half)
$stmt = $pdo->prepare('SELECT * FROM abc WHERE uid = ? ORDER BY id ASC LIMIT ?');
$stmt->bindValue(1, $uid, PDO::PARAM_STR);
$stmt->bindValue(2, $startIndex, PDO::PARAM_INT);
$stmt->execute();
$masterRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 3) fetch partner (remaining rows)
$stmt = $pdo->prepare('SELECT * FROM abc WHERE uid = ? ORDER BY id ASC LIMIT ?, ?');
$stmt->bindValue(1, $uid, PDO::PARAM_STR);
$stmt->bindValue(2, $startIndex, PDO::PARAM_INT);
$stmt->bindValue(3, $remaining, PDO::PARAM_INT);
$stmt->execute();
$partnerRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Important details, edge cases and tips

  • LIMIT offset,count: offset is zero-based. To get rows 0..11 use LIMIT 0,12. To get rows 12..24 use LIMIT 12,13 (if total is 25).
  • If you only supply one value to LIMIT (LIMIT 12) it means LIMIT 12 which returns the first 12 rows (offset 0).
  • When calculating the second query, the second parameter must be the number of rows to return: remaining = total - startIndex.
  • Always use ORDER BY (for example on a primary key column) to ensure the split is deterministic.
  • For large data sets consider pagination (offset can be expensive for large offset values) or keyset pagination (seek method) instead of offset-based LIMIT.
  • Validate and cast integer values before using them in SQL. Never interpolate untrusted strings into queries.

Example using COUNT(*) then a single-step fetch for Master

// count
$stmt = $pdo->prepare('SELECT COUNT(*) FROM abc WHERE uid = ?');
$stmt->execute([$uid]);
$total = (int)$stmt->fetchColumn();
$half = intdiv($total, 2);

// fetch Master
$stmt = $pdo->prepare('SELECT * FROM abc WHERE uid = ? ORDER BY id ASC LIMIT ?');
$stmt->bindValue(1, $uid, PDO::PARAM_STR);
$stmt->bindValue(2, $half, PDO::PARAM_INT);
$stmt->execute();
$masterRows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Summary / Conclusion

The main trick in the original post is the LIMIT clause — it lets you restrict rows returned. But to make the split correct and safe:

  • Use COUNT(*) to get the total.
  • Use ORDER BY to make the split deterministic.
  • Use LIMIT offset,count with the correct remaining count for the second query.
  • Use mysqli or PDO with prepared statements instead of deprecated mysql_* functions to avoid security issues.

Happy Coding!

Thursday, May 12, 2016

Add a Splash Screen in Android Studio — 3‑Second Example (Updated Best Practices)

Most of the Android apps use a splash screen before launching their main activity; you can see this with popular apps such as Skype, Facebook, Dropbox, etc.

While I was developing an Android APP POC for one of my customer, the requirement was to create a splash screen with their logo which stays on the screen for 3 seconds. Below are clear steps and code examples you can follow.

Prerequisites

  • Android Studio (recommended recent stable version)
  • A new or existing Android project
  • A splash image (eg. splash_image.jpg) to place in your project's drawable folders

Overview

Two common approaches:

  1. Theme-based launch screen (recommended for fastest cold start)
  2. Separate Splash Activity (simple to implement — retains the author’s original approach)

This article preserves the original example and also shows a modern, safer implementation.

1) Create a new project in Android Studio

  1. File -> New Project
  2. Enter Application Name and Minimum SDK, Click Next
  3. Select Blank Activity, Click Next
  4. Click Finish

This creates the Android application with a blank activity. Next we will add the splash screen.

2) Create the splash layout

Create a layout file named res/layout/splash.xml with a simple LinearLayout that uses a drawable as the background. (The original article used a background drawable named splash_image.)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/splash_image">
</LinearLayout>

Place your splash image file (for example splash_image.jpg) into your app/src/main/res/drawable or into density-specific folders like drawable-hdpi, drawable-xhdpi depending on your asset. For images that should not be scaled by Android, use drawable-nodpi.

3) Original (author's) Splash Activity example

The original sample shows a Splash Activity that waits for 3 seconds and then launches MainActivity. The unmodified original code (kept for reference) is shown below.

// SplashScreen.java
package marutsoft.vehicledata;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Display;
import android.widget.ImageView;

/**
 * Created by Karjol G T on 11-05-2016.
 */
public class SplashScreen extends Activity {

    protected int _splashTime = 3000;
    private Thread splashThread;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Display display = getWindowManager().getDefaultDisplay();
        setContentView(R.layout.splash);

        Thread timerThread = new Thread(){
            public void run(){
                try{
                    sleep(3000);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }finally{
                    Intent intent = new Intent(SplashScreen.this,MainActivity.class);
                    startActivity(intent);
                }
            }
        };
        timerThread.start();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        finish();
    }
}

Notes on the original approach:

  • This uses a background thread and sleep(3000). While it works in many cases, it is not the recommended pattern for modern Android apps. If misused it can block the UI or cause unexpected lifecycle behavior.
  • onPause() calls finish() to ensure the splash activity is removed from the back stack.

4) Manifest entry (make the splash activity the launcher)

Add the splash activity to your AndroidManifest.xml and make it the LAUNCHER activity. (Keep your package name.) The original manifest snippet:

<activity
    android:name=".SplashScreen"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
</activity>

5) Recommended modern implementation (non-blocking)

A safer and simpler approach is to use a Handler.postDelayed(...) from the UI thread (or new Handler(Looper.getMainLooper()) on newer platforms). Also prefer AppCompatActivity (or AndroidX ComponentActivity / AppCompatActivity) and call finish() after starting the main activity so the user does not return to the splash.

// SplashScreen.java (recommended modern approach)
package marutsoft.vehicledata;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity; // or import android.support.v7.app.AppCompatActivity for older projects

public class SplashScreen extends AppCompatActivity {

    private static final long SPLASH_DELAY_MS = 3000L; // 3 seconds

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(intent);
                finish(); // remove SplashScreen from back stack
            }
        }, SPLASH_DELAY_MS);
    }
}

Why this is better:

  • No manual Thread management or sleeping; uses Android's message queue and is safe on modern devices.
  • Cleaner lifecycle handling when you call finish() after starting the main activity.
  • Uses AppCompat so it's straightforward to compile in modern Android Studio projects.

6) Alternative best-practice: theme-based launch screen

For fastest cold start it is recommended to use a theme-based splash implemented with windowBackground in your app theme. This avoids inflating a layout or starting an activity before the first frame is shown. In short:

  • Create a drawable (or layer-list) for the splash look
  • Set it as windowBackground in a launch theme
  • Use that theme for your LAUNCHER activity in the manifest

This method provides the fastest perceived startup time and is the recommended pattern for production apps. See the linked resources at the end for a dedicated guide.

7) Additional notes and troubleshooting

  • Rotation: if your splash activity must survive rotation, avoid re-posting delayed callbacks multiple times. You can lock orientation or keep the activity lightweight.
  • Long startup work: do not perform heavy initialisation on the UI thread during splash. Offload to background threads and show progress only if necessary.
  • Assets: put different density images in drawable-*/ folders or use drawable-nodpi if you do not want Android to scale the image.
  • Accessibility: when displaying logos in a view, provide content descriptions for screen readers. In a background-only layout, ensure the important content is accessible elsewhere in the app.

8) Run the app

Run the Android application to check the splash screen running at the beginning of the application.

That's it. Happy Coding..


Created by Karjol G T (original example preserved).

Saturday, May 7, 2016

Sorting Multidimensional Arrays in PHP — array_multisort and usort Examples

I was working on a project. I had to do a lot of interaction between a MySQL server and my Android app. In that case I got a situation where I get the raw data from the database which I needed to sort and show on the fly. This data is in a multi-dimensional array.

Problem

I used to get the items data from MySQL based on the user id, build a products array, and then sort it by the bay value so the app can consume ordered results.

Original code (as used in the project)

The original code used mysql_* functions and built the array like this:

$result = mysql_query("SELECT * FROM savedlist where uid='$uid' ") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
    $response['products'] = array();
    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $itemtypes = array();
        $itemtypes['id']=$row['pid'];

        $result1 = mysql_query("SELECT * FROM items where id='$row[pid]'") or die(mysql_error());

        while ($row1 = mysql_fetch_array($result1)) {
            $itemtypes['name'] = $row1['name'];
            $itemtypes['price']=$row1['price'];
            $itemtypes['bay']=$row1['bay'];
        }

        print_r($itemtypes, true);
        // push single product into final response array
        array_push($response['products'], $itemtypes);

        $bays = array();
        foreach ($response['products'] as $bay)
        {
            $bays[] = $bay['bay'];
        }

        array_multisort($bays,SORT_ASC, $response['products'] );
    }
}

Here $response['products'] is a multi-dimensional array which the author wanted to sort based on the BAY. So first a separate $bays[] array is created from each product's 'bay' value and then array_multisort() is used.

Note: The article later shows an alternate call: array_multisort($response['products'], SORT_ASC, $bays); — this is the wrong order for what the author intended. The correct form is shown below.

Correct usage of array_multisort for this case

array_multisort sorts arrays in parallel: you pass the array of sort keys first, then the order and finally the array(s) you want reordered to match. For the example above the correct call is:

array_multisort($bays, SORT_ASC, $response['products']);

This ensures $bays is used as the sort key and $response['products'] is re-ordered to match that sorted key array.

Why order matters

array_multisort uses the first array you pass as the primary sort key. If you pass the data array first it will try to sort that array directly (which is not what you intended) and the $bays array will be treated as a secondary array.

A simpler and often clearer alternative: usort

For sorting a single key inside an array of associative arrays, usort with a comparison function is usually easier and more readable:

usort($response['products'], function($a, $b) {
    // PHP 7+ spaceship operator:
    return $a['bay'] <=> $b['bay'];
});

// or, if you prefer ascending numeric comparison without spaceship:
usort($response['products'], function($a, $b) {
    if ($a['bay'] == $b['bay']) return 0;
    return ($a['bay'] < $b['bay']) ? -1 : 1;
});

usort modifies $response['products'] in place and is often the most straightforward choice when you only need to sort by one field.

Example: build then sort (complete flow)

Here's a clearer flow that keeps the original structure but shows the sorting step separately. (This still uses the original mysql_* calls — see the modernization note below.)

$response['products'] = array();

// -- build the products array (as original) --
// ... (database fetch loops from original code) ...
// after pushing all $itemtypes into $response['products']

// build the key array
$bays = array();
foreach ($response['products'] as $product) {
    $bays[] = $product['bay'];
}

// sort by bay ascending and reorder products to match
array_multisort($bays, SORT_ASC, $response['products']);

// or, using usort (recommended for single-key sorts):
usort($response['products'], function($a, $b) {
    return $a['bay'] <=> $b['bay'];
});

// final output example (JSON for mobile app):
echo json_encode($response, JSON_PRETTY_PRINT);

Important modernization and security notes

  • The mysql_* extension used in the original code has been removed from PHP as of PHP 7 and is deprecated. For new code use mysqli (procedural or object oriented) or PDO with prepared statements to avoid SQL injection and to be compatible with current PHP versions.
  • Avoid using die(mysql_error()) in production. Handle errors gracefully and do not reveal internal database errors to end users.
  • If you are building an API consumed by an Android app, ensure you return properly encoded JSON and set appropriate response headers.

When to use array_multisort vs usort

  • Use array_multisort when you need to sort by multiple columns with different sort directions (it can sort multiple arrays in tandem).
  • Use usort when you sort by a single key (or when you prefer a comparison function); usort tends to be clearer for single-key sorts and easier to read/maintain.

References

That's it. Happy Coding

Thursday, May 5, 2016

Download Durmukhi Naam Samvastara (SRSM Panchanga) — English Version Available

Greeting of the Day!!!

First of all I am very sorry for delaying in updation of Durmukhi Naam Samvastara data. And thanks to all those who written to me to update it. Now it's updated and the app is ready to download with all the data for Durmukhi Naam Samvastara.

Download

The updated SRSM Panchanga app (Durmukhi Naam Samvastara) is available to download from the Google Play Store:

https://play.google.com/store/apps/details?id=com.sarga.simplecal

Please uninstall the older version of the application if installed and install this new version.

App details (update these from Play Store when editing)

  • App name: SRSM Panchanga (Durmukhi Naam Samvastara)
  • Language: English (Kannada version coming soon)
  • Where to download: Google Play Store (link above)

Note: When updating the live post, include exact Play Store metadata such as version number, APK size, required Android version, and release date. Do not add those here unless taken directly from the Play Store listing.

How to install

  1. Open the Play Store link above on your Android device or visit the page from a desktop browser.
  2. If you have an older version installed, uninstall it first:
  • Settings → Apps → SRSM Panchanga → Uninstall
  1. Tap "Install" on the Play Store page.
  2. Once installed, open the app and verify the data is updated.

Notes

  • The app is currently available in English. Kannada version will be available soon.
  • Thank you to everyone who wrote in requesting the update — your feedback helped prioritize this release.

Contact / Feedback

If you face issues or want to report problems with the data, please reply to this post or use the blog's contact mechanism to let me know.