harun
harun

Reputation: 11

Loop through database for a particular record and show results - PHP

i'm looking for a way to loop through the database and shows results in a html page, i'm actually creating a sorta fake email system for a little project.

so i have a table name "SENDS" with 5 columns ID, Mailtext, Touser, Subject, Fromuser. what i wanna do is when user log in system connects to the database and select everything from SENDS where touser='$email' -$email is defined when user logs in- and display it in a html div

<div class="oubx">
  <div class="inbx">
   <span class="from"></span>
   <span class="subject"></span>
   <span class="mailtext"></span>
  </div>
 </div>

.oubx {
	height:27px; width:800px;
	border:1px solid black;
	margin-top:;
	margin-left:80px;
	float:left;
	background-color:white;
}

.inbx {
	height:22px; width:700px;
	border:1px solid black;
	margin-top:1px;
	margin-left:45px;
	background-color:white;
	font-family:sans-serif;
	font-weight:bold;
	font-size:16px;
	color:#808080;
	float:left;
}

from of course tells whos it from

subject is subject

mailtext is what the mail is (it's hidden of course jQ will take care of it once clicked)

i have used mysqli_num_rows, mysqli_fetch_array, for loops, foreach etc but i just can't seem to get my head around it i'm having a hard time figuring out how to do it setp by steps or what the step is. please help :) thanks.

$connectDB = mysqli_connect("host","root","","db");

$touser = mysqli_query($connectDB, "select * from sends where touser='$email'");
$to_numrows = mysqli_num_rows($touser);
$to_fetch = mysqli_fetch_array($touser);

//printing of html code = how many rows  
$ib = '<div class="oubx"><div class="inbx"><span class="from">'.$value.'</span><span class="subject">'.$value.'</span></div></div>';
for ($i = 0; $i < $to_numrows; $i++) {
 echo $ib;
}

the rest is work in progress..

Upvotes: 0

Views: 1258

Answers (2)

php-dev
php-dev

Reputation: 7156

Try this,

$connectDB = mysqli_connect("host","root","","db");

$touser = mysqli_query($connectDB, "select * from sends where touser = '$email'");
$all_rows = mysqli_fetch_all($touser, MYSQLI_ASSOC);

$ib = '';

foreach($all_rows as $row) {  
    $ib .= '<div class="oubx">'
         . '<div class="inbx">' 
         . '<span class="from">' . $row['Fromuser'] . '</span>'
         . '<span class="subject">' . $row['Subject'] . '</span>'
         . '</div>'
         . '</div>';
}

echo $ib;

1- mysqli_fetch_all will fetch all result row into a PHP array
2- We loop through it with foreach (no need to know the rows count)
3- Foreach row, we append the HTML to the $ib intially set to empty string.

Hope it helps.

Upvotes: 0

Nitsan Baleli
Nitsan Baleli

Reputation: 5458

put the query result in a variable:

while ($row = $touser->fetch_array()) {
  $rows[] = $row;
}

and iterate it with a loop:

foreach ($rows as $row) {
  /* show appropriate html here */
}

Upvotes: 0

Related Questions