i am trying to fetch the data from the database using the for loop format but the loop is execute but but the data cannot be retrived.
this is my php code
$resultss = array_unique($Employeeids);
// echo sizeof($resultss);
for($i = 0; $i<=sizeof( $resultss); $i++)
{
//echo $resultss[$i]. "<br>";
if($resultss[$i] !='')
{
$uniqueemp_id[$i]=$resultss[$i];
echo $uniqueemp_id[$i]."hi". "<br>";
$sql[$i]="Select Token From user Where Employeeid= '".$uniqueemp_id[$i]."'";
$result[$i]=mysqli_query($con,$sql[$i]);
echo $sql[$i];//upto here loop is executing correctly but while is not executing.
while($row = mysqli_fetch_assoc($result[$i]))
{
echo $tokens = $row['Token']. "<br>";
}
mysqli_close($con);
}
}
i can able to fetch and display the token of employee id 9 but not able to display the token of employee id 15 ,i cannot able to find what is the error can anyone help me to fix this issue!
Your core issue is that you close the connection ( mysqli_close
) at the end of the first iteration. Move that to at least outside and below your loop.
There are a number of chances for code improvement here. I was going to ignore them, until I saw the lack of prepared statements. In assorted order.
At least in the snippet provided, there is no need for $i
. Just use foreach, and cleanup the ensuing references to $i
:
foreach ( $resultss as $empId ) {
Styling wise, save yourself some indentation with continue
. Rather than
if($empId != '') { ...
use:
if ( ! $empId ) continue; ...
Unless you need $uniqueemp_id
later, just don't use it at all. Stick with $empId
In general, get in the habit of using prepared statements with bound parameters. It's a security thing, it's a performance thing, it's a simplicity thing, it's good habit. Just do it.
Prepare a single query, and execute it multiple times, or get all of the results with the IN
SQL operator. A single prepared query executed multiple times:
$sql = 'SELECT token FROM user WHERE employeeid = ?'; $sth = mysqli_prepare($con, $sql); # "statement handle" if ( ! $sth ) die('Unable to create prepared statement'); foreach ( $resultss as $empId ) { ... mysqli_stmt_bind_param($sth, "s", $empId); mysqli_stmt_execute( $sth ); $result = $sth->get_result(); while ($row = $result->fetch_assoc()) echo "Token: {$row['token']}<br>"; }
I'll leave the IN
operator as an "exercise to the reader".
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.