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)
- Deprecated API: the examples use the old
mysql_*extension which is removed in modern PHP. UsemysqliorPDOwith prepared statements. - Security: variables are interpolated into SQL directly (
'$uid') — this allows SQL injection. Use parameterized queries. - Wrong LIMIT usage in the partner query:
LIMIT $startindex,$totalrowsis incorrect because the second parameter is the number of rows to return, not the final index. If$totalrowsis the total number of rows, you should useLIMIT $startindex, $totalrows - $startindex. - No ORDER BY: without ORDER BY the split is nondeterministic.
- 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)
- Get total rows using COUNT(*):
SELECT COUNT(*) AS total FROM abc WHERE uid = ?
- 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;
- 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.)
- 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!