tisaconundrum
tisaconundrum

Reputation: 2292

PHP/SQL Stuck in an inifinite while loop possibly due to a bad query?

$query = "SELECT DISTINCT users FROM computers WHERE ComputerName='EN4073254W'";
while ($user_name = mysqli_fetch_array(mysqli_query($cxn, $query))) { // print out user names
    printf("<li><a href='%s'>%s</a>\n", $user_name[0], $user_name[0]);
}

I am running a query to check for distinct users based on ComputerName all of this is ran through a while loop, I did this by following an example I found here. Running this query in phpMyAdmin results in correct output, so I'm roughly confident that my query is correct. I've also spent the time chopping through this line by line in phpStorm's debugger, but alas it gives me no good insight into what is happening (it just repeats itself over and over again).

<li><a href='foo'>foo</a>
<li><a href='foo'>foo</a>
<li><a href='foo'>foo</a>
<li><a href='foo'>foo</a>
<li><a href='foo'>foo</a>
<li><a href='foo'>foo</a>
<li><a href='foo'>foo</a>
...

The desired result should be something like this

<li><a href='foo'>foo</a>
<li><a href='bar'>bar</a>

Upvotes: 0

Views: 77

Answers (3)

jvk
jvk

Reputation: 2201

$query = "SELECT DISTINCT users FROM computers WHERE ComputerName='EN4073254W'";
$stmtQuery = mysqli_query($cxn, $query);
while ($user_name = mysqli_fetch_array($stmtQuery)) { 
    printf("<li><a href='%s'>%s</a>\n", $user_name[0], $user_name[0]);
}

Upvotes: 2

prasanna puttaswamy
prasanna puttaswamy

Reputation: 987

You are executing query in while loop so its running infinite time.

 while ($user_name = mysqli_fetch_array(mysqli_query($cxn, $query))) // runs infinite time 

change the above line to

$result = mysqli_query($cxn, $query);
while ($user_name = mysqli_fetch_array(($result,MYSQLI_NUM)))

Upvotes: 2

Luke Schlather
Luke Schlather

Reputation: 397

Your query is fine, but you're re-executing it every time you check to see if you exit the while loop and fetching the first item.

You want something more like: $users = mysqli_fetch_array(mysqli_query($cxn, $query)) foreach ($users as $user_name) { ... }

Upvotes: 0

Related Questions