HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpModerate

Two while for the same query

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
samethewhilequerytwofor

Problem

If I have to loop results of a query echoing first all fields of a column, then echoing something not to loop, then fields of another column.

';
//select the fields of the first column
$query1 = mysqli_query($con,"SELECT user FROM ris_uinversita LIMIT 0,10");
//loop the results
while($assoc1=mysqli_fetch_assoc($query1)){echo $assoc1['user'].'';}
//echo something not to loop
echo 'Users got the following scores';
//select the fields of the second column
$query2 = mysqli_query($con,"SELECT score FROM ris_universita LIMIT 0,10");
//loop the results
while($assoc2=mysqli_fetch_assoc($query2)){echo $assoc2['score'].'';}
?>


Is it possible to use just one query like this

mysqli_query($con,"SELECT * FROM ris_universita LIMIT 0,10");


to select both fields just once?

If it could be helpful, table ris_universita has just the two columns: "score" (tinyint) and "user" (varchar 30). There aren't so many records for now, but I hope in there will be in the future.

Solution

A few things here:

Comments:

Your comments are all compeletely useless.. nothing personal and no offense. That is a beginner-mistake. You don't need to comment everything.

Comments should explain the why and not the how or the what. Exceptions:

  • License comments



  • Documentation (python's docstring, java's javadoc, c#'s summary, ...)



Naming:

$con = //...
$query1 = //...
$assoc1 = //...


As opposed to what many people seem to think, source code characters are not costly. Spell it out:

$connection = //...
$userQuery = //...
$userRecord = //...


Formatting:

The convention is, to place subordinate blocks in a visually different place than surrounding code. This is usually done by indenting the block and putting it on a separate starting line

while($assoc1=mysqli_fetch_assoc($query1)){echo $assoc1['user'].'';}


then becomes:

while ($userRecord = mysqli_fetch_assoc($userQuery)) {
    echo $userRecord['user'].'';
}


This would definitely improve the readability of your code, as one line is not a whole loop! Putting too much on one line makes it extremely difficult to follow the thoughts behind your code and makes reading a pain.

Code Snippets

$con = //...
$query1 = //...
$assoc1 = //...
$connection = //...
$userQuery = //...
$userRecord = //...
while($assoc1=mysqli_fetch_assoc($query1)){echo $assoc1['user'].'<br>';}
while ($userRecord = mysqli_fetch_assoc($userQuery)) {
    echo $userRecord['user'].'<br>';
}

Context

StackExchange Code Review Q#55973, answer score: 11

Revisions (0)

No revisions yet.