I need help understanding how to “efficiently” extract one field/column/cell (that is, one piece of information) from one row of a MySQL table using Procedural Style. The horridly long method would be something like:
$Qry = "SELECT Surname FROM SurnameList WHERE SID = 8 LIMIT 1";
$QryResult = mysqli_query($DBLink, $Qry);
if ($QryResult)
{
$QryRow = mysqli_fetch_assoc($QryResult);
$ThisSurname = $QryRow['Surname'];
mysqli_free_result($QryResult);
}
else
{
die("Transaction Failure");
}
Uggg. For me, this can be compacted while still retaining readability:
if ($QryResult = mysqli_query($DBLink, "SELECT Surname FROM SurnameList WHERE SID = 8 LIMIT 1") {
$QryRow = mysqli_fetch_assoc($QryResult);
$ThisSurname = $QryRow['Surname'];
mysqli_free_result($QryResult);
} else die("Transaction Failure");
Even compacted like this, it still takes 5 lines to get one piece of information. Isn't there a way to reduce the line count for this task within Procedural Style while retaining readability? Some way to compact/combine lines 2 and 3?
Your code is short enough that you aren't meaningfully impacting 'efficiency' at the parser. That said, you can trim a few lines by reversing your conditional to die only if the query fails (general tip, design code to avoid using else) and one-line fetching your desired result.
$QryResult = mysqli_query($DBLink, "SELECT Surname FROM SurnameList WHERE SID = 8 LIMIT 1");
if (!$QryResult) die("Transaction Failure");
$ThisSurname = mysqli_fetch_assoc($QryResult)['Surname'];
mysqli_free_result($QryResult);
I think you would be well served to consider classes to handle repeatable logic like this if you are after coding efficiency :).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.