I have a while and foreach loop that I want to use to print all of my results from a MySQL query. Below is my code for the while statement and the foreach statements.
WHILE:
while ($row_questions = mysql_fetch_array($result_questions)) {
$step_number[] = $row_questions['step_number'];
if ($row_questions['step_number_sub'] != 0) {
$step_number_sub[] = $row_questions['step_number_sub'];
} else {
$step_number_sub[] = "0";
};
if ($row_questions['step_required'] != 0) {
$step_required[] = "*";
} else {
$step_required[] = "";
};
$step_description[] = $row_questions['step_description'];
$step_outcome[] = $row_questions['step_outcome'];
$step_equipment[] = $row_questions['step_equipment'];
$test_changes[] = $row_questions['test_changes'];
};
and my FOREACH:
foreach ($step_number as $i => $step){
$even_odd = ( '-odd' != $even_odd ) ? '-odd' : '';
echo '<section class="zebra'.$even_odd.'">';
echo '<div class="span-2 number"><strong>'.$step_number[$i].'</strong></div>';
echo '<div class="span-20 description">'.$step_description[$i].'</div>';
echo '<div class="span-2">'.$step_required[$i].'</div>';
if ($step_outcome[$i] != null) {
echo '<div class="span-22 outcome"><strong>Desired Outcome</strong><br>'.$step_outcome[$i].'</div>';
}
echo '<div class="clear"></div>';
echo '<article class="results">';
echo '<div class="span-10">Did this step match the desired outcome?</div>';
echo '<div class="span-10">Notes:</div>';
echo '<div class="span-10">
<select name="question_'.$step[$i].'" id="question_'.$step[$i].'" required aria-required="true">
<option name="pass" value="Pass">Yes, this step was completed successfully</option>
<option name="fail" value="Fail">No, this step failed to complete. See notes below</option>
</select>
</div>';
echo '<div class="span-10"><textarea name="question_'.$step[$i].'" id="question_'.$step[$i].'" class="nots"></textarea></div>';
echo '</article>';
echo '<div class="clear"></div>';
echo '</section>';
};
I am getting multiple versions of the same results (4). Thanks in advance for any help and let me know if you need any other info!
Don't use multiple arrays. Use a class structure or array for each element. A simple way to do this:
while ($row_questions = mysql_fetch_array($result_questions))
questions[] = $row_questions;
foreach( $questions as $question )
{
$even_odd = ( '-odd' != $even_odd ) ? '-odd' : '';
echo '<section class="zebra'.$even_odd.'">';
echo '<div class="span-2 number"><strong>'.$question['step_number'].'</strong></div>';
echo '<div class="span-20 description">'.$question['step_description'].'</div>';
echo '<div class="span-2">'.$question['step_required'].'</div>';
if ($question['step_outcome'] != null)
{
echo '<div class="span-22 outcome"><strong>Desired Outcome</strong><br>'.$question['step_outcome'].'</div>';
}
... you get the drift ...
};
Related
I have a problem regarding my foreach loop wherein i cannot access the first array or the array[0] and i dont know the problem.
here is the controller:
$this->SessionCheck();
$this->user->initialize($this->session->userdata('userid'));
$this->load->model('project_model', 'Project');
$ProjectID = $this->input->post('ProjectID');
/***************** Intialize Project model ******************/
$this->Project->Initialize($ProjectID);
$Options = Work_breakdown_structure::$WithBaseTaskID;
//$PhaseTaskID = (int)$this->input->get_post('TaskID',TRUE);
$PhaseTaskID = $this->Project->getPhaseBaseTaskID($ProjectID);
$postlist->PhaseTaskID = $this->Project->getPhaseBaseTaskID($ProjectID);
$postlist->phaseList = $this->Project->LatestApplicablePlan->WBS->GetPhaseList($Options);
if($PhaseTaskID == null)
{ }
else
{
foreach($PhaseTaskID as $index=>$value)
{
$finalArr[$value['TaskName']] = $value['BasetaskID'];
$postlist->taskList = $this->Project->LatestApplicablePlan->WBS->GetWBS($finalArr[$value['TaskName']], $Options);
}
echo print_r($finalArr);
for($x = 1 ; $x < 2 ; $x++)
{
//$postlist->taskList = $this->Project->LatestApplicablePlan->WBS->GetWBS($phaseID, $Options);
}
}
$postlist->project = $ProjectID;
return $this->load->view('MyToDoPhaseDropdown', $postlist);
here is my view:
echo '<td style="padding-top:5x;font-size:14px;" colspan="2"> <br> Phases : ';
echo '<select id="phases_select" style="width:400px;" onchange="search_filter()" >';
echo '<option value="0" selected="selected"> Select Project Phase </option>';
foreach($phaseList as $row)
{
if(preg_match("/^CYCLE/", strtoupper($row['TaskName'])))
{
foreach($row['Child'] as $child)
{
echo '<option value="'. $child['TaskID']. '">';
echo $row['TaskName'].' > '.$child['TaskName'] . '</option>';
}
}
else
{
if($Iterate['BaseTaskID'] != $row['TaskID'])
{
echo '<option value="'. $row['TaskID']. '">';
echo $row['TaskName'].'</option>';
}
foreach($taskList as $Iterate)
{
if($row['TaskID'] == $Iterate['BaseTaskID'] )
{
echo '<option value="'. $row['TaskID']. '">';
echo $Iterate['TaskName'].' '.$Iterate['IterationNumber']. '</option>';
}
}
}
}
echo '</select>';
echo '</td>';
The problem is that i need to get all the values into an array to pass it to the view. but i only get the latest value which is the 2nd data that i retrieve in the database.
What you are doing wrong is :
return $this->load->view('MyToDoPhaseDropdown', $postlist);
You need to set the data in a variable to be accessible in view : http://codeigniter.com/user_guide/general/views.html
$data = array('title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message');
$this->load->view('MyToDoPhaseDropdown', $data);
And in view file : MyToDoPhaseDropdown.php
<html>
<?php
//Access them like so
echo $title.$heading.$message; ?>
</html>
I have a problem wherein i will retrieve several datas in my sql, for example i have 9 datas but my problem is that inside my foreach the data that will be process and the foreach is placed in my controller.
here's my controller:
function getPhaseData() {
try
{
$this->SessionCheck();
$this->user->initialize($this->session->userdata('userid'));
$this->load->model('project_model', 'Project');
$ProjectID = $this->input->post('ProjectID');
/***************** Intialize Project model ******************/
$this->Project->Initialize($ProjectID);
$Options = Work_breakdown_structure::$WithBaseTaskID;
//$PhaseTaskID = (int)$this->input->get_post('TaskID',TRUE);
//$PhaseTaskID = $this->Project->getPhaseBaseTaskID($ProjectID);
$postlist->phaseList = $this->Project->LatestApplicablePlan->WBS->GetPhaseList($Options);
$PhaseList = $this->Project->LatestApplicablePlan->WBS->GetPhaseList($Options);
foreach($PhaseList as $row)
{
$postlist->taskList = $this->Project->LatestApplicablePlan->WBS->GetWBS($Iterate['TaskID'], $Options);
}
/*if($PhaseTaskID == null)
{ }
else
{
foreach($PhaseTaskID as $index=>$value)
{
$finalArr[$value['baseTaskID']] = $value['baseTaskID'];
//echo $finalArr[$value['baseTaskID']].' ';
$postlist->taskList = $this->Project->LatestApplicablePlan->WBS->GetWBS($finalArr[$value['baseTaskID']], $Options);
}
}*/
$postlist->project = $ProjectID;
return $this->load->view('MyToDoPhaseDropdown', $postlist);
}
here's my view where i will display the data get from the controller in my select dropdown.
if($project == 0) {
echo '<td style="padding-top:5x;font-size:14px;" colspan="2"> <br> Phases : ';
echo '<select disabled id="phases_select" style="width:400px;" onchange="search_filter()" >';
echo '<option value="0" selected="selected"> Select Project Phase </option>';
echo '</select>';
echo '</td>';
}
else
{
foreach($taskList as $iterate)
{
echo ' TaskID: '. ' '.$iterate['TaskID'] .' -- TaskName: '. $iterate['TaskName'].'<br>' ;
}
/*foreach($phaseList as $row) {
echo 'TaskID: '. $row['TaskID'].' '.$row['TaskName'].'<br>';
if(preg_match("/^CYCLE/", strtoupper($row['TaskName'])))
{
foreach($row['Child'] as $child) {
echo 'TaskID: '. $child['TaskID'].' '.$child['TaskName'].'<br>';
}
}
}*/
echo '<td style="padding-top:5x;font-size:14px;" colspan="2"> <br> Phases : ';
echo '<select id="phases_select" style="width:400px;" onchange="search_filter()" >';
echo '<option value="0" selected="selected"> Select Project Phase </option>';
foreach($phaseList as $row)
{
if(preg_match("/^CYCLE/", strtoupper($row['TaskName'])))
{
foreach($row['Child'] as $child)
{
if($Iterate['BaseTaskID'] != $child['TaskID'])
{
echo '<option value="'. $child['TaskID']. '">';
echo $row['TaskName'].' > '.$child['TaskName']. '</option>';
}
foreach($taskList as $Iterate)
{
if($child['TaskID'] == $Iterate['BaseTaskID'])
{
echo '<option value="'. $Iterate['TaskID']. '">';
echo $row['TaskName'].' > '.$child['TaskName'].' '.$Iterate['IterationNumber']. '</option>';
}
}
}
}
else
{
if($Iterate['BaseTaskID'] != $row['TaskID'])
{
echo '<option value="'. $row['TaskID']. '">';
echo $row['TaskName'].'</option>';
}
foreach($taskList as $Iterate)
{
if($row['TaskID'] == $Iterate['BaseTaskID'] )
{
echo '<option value="'. $Iterate['TaskID']. '">';
echo $row['TaskName'].' '.$Iterate['IterationNumber']. '</option>';
}
}
}
}
echo '</select>';
echo '</td>';
}
This is not on exact answer but this will help to understand MVC structure in codeigniter.
model
function get_city_list(){
$this->db->select('city_id, name');
$this->db->where('status', 1);
$this->db->order_by("name", "asc");
$this->db->from('city');
$query = $this->db->get();
$result = $query->result();
return $result;
}
Controller
function listing(){
$data['city'] = $this->home->get_city_list();
$this->load->view('property_listing', $data);
}
view
foreach($city as $cty){
echo $cty->name;
echo $cty->city_id;
}
Hope this helps you..
I have this JOIN, that gets me more than on result:
at.tipo AS atividade,
at.data AS datacadastro,
at.user AS usercadastro,
LEFT JOIN atividades at
ON (at.produto = '$produto')
AND (at.tipo = 'cadastra' OR at.tipo = 'revisado')
And I have: if string = 'cadastra' shows something, if string = 'revisado' shows something else.
<?php
if ($row['atividade'] == 'cadastra') {
echo '<div id="user-img">';
echo '<img src="http://'.$row['imguser'].'"/></div>';
echo '<div id="user-cadastro" class="greytxt">';
echo 'Cadastrado por <br>' .$row['usercadastro']. '<br>em ';
echo $row['datacadastro']. '</div>';
}
?>
<?php
if ($row['atividade'] == 'revisado') {
echo '<div id="user-img">';
echo '<img src="http://'.$row['imguser'].'"/></div>';
echo '<div id="user-cadastro" class="greytxt">';
echo 'Cadastrado por <br>' .$row['usercadastro']. '<br>em ';
echo $row['datacadastro']. '</div>';
}
?>
The problem is, it's showing just the first result, and not all.
How can I display all results?
EDIT:
I have this JOIN inside a big query, that give me other important rows.
But I just want one result for this principal query (WHERE = $produto), and want more results from my JOIN table.
$rows = $result->num_rows;
for ($j = 0; $j < $rows; ++$j) {
$result -> data_seek($j);
$row = $result->fetch_array (MYSQLI_ASSOC);
?>
My result should be this, but JOIN shows just row 'cadastra'.
Use $result->fetch_array (MYSQLI_ASSOC) inside a while loop
while ($row = $result->fetch_array (MYSQLI_ASSOC)) {
if ($row['atividade'] == 'cadastra')
{
echo '<div id="user-img">';
echo '<img src="http://'.$row['imguser'].'"/></div>';
echo '<div id="user-cadastro" class="greytxt">';
echo 'Cadastrado por <br>' .$row['usercadastro']. '<br>em ';
echo $row['datacadastro']. '</div>';
} ?>
<?php if ($row['atividade'] == 'revisado')
{
echo '<div id="user-img">';
echo '<img src="http://'.$row['imguser'].'"/></div>';
echo '<div id="user-cadastro" class="greytxt">';
echo 'Cadastrado por <br>' .$row['usercadastro']. '<br>em ';
echo $row['datacadastro']. '</div>';
}
}
I'm running a while loop which is taking rows from mySQL and echo'ing them out. Pretty standard. However, there needs to be different HTML markup for the first item, next two items, then it continues as normal into the while loop.
Currently, my while loop looking something like this:
while( ( $row = mysql_fetch_object( $result ) ) !== false )
{
// Places ad based of predefined variable frequency
if ($ad == $adFrequency){
echo '<div class="one-advertisement-article clearfix">';
echo '<div class="grid_9 suffix_2"><img src="http://placehold.it/263x75/000000/ffffff"></div>';
echo '<div class="grid_1"><a class="navigate-right-icon ss-icon" href="#">navigateright</a></div>';
echo '</div>';
$ad = 0;
}
echo '<div class="one-news-article clearfix">';
if( $row->imagelibid )
{
$imageid = intval( $row->imagelibid );
$image_result = mysql_query( "SELECT * FROM imagelib WHERE id = {$imageid}", $db );
$image_row = mysql_fetch_object( $image_result );
$image_url = "http://www.#.com/slir/w280/imagelib/" . $image_row->id . "_" . $image_row->filename;
echo '<div class="grid_4"><img src="'.$image_url.'"></div>';
}
else {
echo '<div class="grid_4"><div class="news-placeholder"><span class="ss-icon">ellipsischat</span></div></div>';
}
echo '<div class="grid_7">';
echo '<h2>'.$row->title.'</h2>';
$published_date = date('D, d M Y', strtotime($row->datein));
echo '<p class="published-date">'.$published_date.'</p>';
echo '</div>';
echo '<div class="grid_1">';
echo '<div class="news-item-vertical-sep"> </div>';
echo '<p></p>';
echo '</div>';
echo '</div>';
$ad++;
}
This works fine, but I need to take the first three news items and use this:
echo ' <div class="one-news-featured-article clearfix">';
echo ' <div class="grid_12">';
if( $row->imagelibid )
{
$imageid = intval( $row->imagelibid );
$image_result = mysql_query( "SELECT * FROM imagelib WHERE id = {$imageid}", $db );
$image_row = mysql_fetch_object( $image_result );
$image_url = "http://www.#.com/slir/w280/imagelib/" . $image_row->id . "_" . $image_row->filename;
echo '<div class="large-featured-image-container"><img src="'.$image_url.'">/div>';
}
echo ' <div>';
echo ' <h2>'.$row->title.'</h2>';
echo ' </div>';
echo ' </div>';
echo ' </div>';
echo ' <div class="grid_6">';
Any help? Essentially, it needs to apply the second code to the first three items in the query, then follow through with the code included in the current while loop - like an offset I guess.
Thanks,
R
This is quite simple. I hope I understood your question correctly:
$i = 0;
while ( ( $row = mysql_fetch_object( $result ) ) !== false ) {
if ($i < 3) {
// First code
} else {
// Second code
}
$i += 1;
}
Firstly, you should avoid using any mysql_ functions as they are all deprecated and will be removed from future versions of PHP. I'd recommend using PDO instead. See this tutorial to get started.
Then, it'll simply be a case of doing something like this:
foreach($db->query($query) as $index => $row) {
if ($index < 3) {
// first 3 items
} else {
// other items
}
}
You can do it easaly with an simple counter and an if statement:
$count = 0;
while(fetching) {
if($count < 3) {
// items 1, 2 and 3
} else {
// do normal
}
$count++;
}
I have a php script that will loop until all the skill, exp and rating variables are displayed that the user entered into the database.
What I want is the following code to only display once and only if the variables are holding info and not empty. How can I do this. I hope I explained it okay.
I want this code displayed first.
echo '<div id="con">';
echo '<h2 id="s">Skills</h2>';
echo '<h2 id="exp">Exp</h2>';
echo '<h2 id="r">Rating</h2>';
Here is the full code.
<?php
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT * FROM skills WHERE user_id='3'");
if (!$dbc) {
print mysqli_error();
}
echo '<div id="con">';
echo '<h2 id="s">Skills</h2>';
echo '<h2 id="exp">Exp</h2>';
echo '<h2 id="r">Rating</h2>';
while ($row = mysqli_fetch_assoc($dbc)) {
if (!empty($row['skill']) || !empty($row['exp']) || !empty($row['rating'])) {
if (! empty($row['skill'])) {
echo '<div class="s">';
echo '<p>' , htmlspecialchars($row['skill']) , '</p>';
}
if (! empty($row['exp'])) {
echo '<div class="s">';
echo '<p>' , htmlspecialchars($row['exp']) , '</p>';
}
if (! empty($row['rating'])) {
echo '<div class="s">';
echo '<p>' , htmlspecialchars($row['rating']) , '</p>';
}
}
}
echo '</div>';
?>
you can take the following after the loop:
echo '<div id="con">';
echo '<h2 id="s">Skills</h2>';
echo '<h2 id="exp">Exp</h2>';
echo '<h2 id="r">Rating</h2>';
and instead of echo in the loops , use vars to store the text and then check if the var holds something and then echo
update:
would become something like this:
$skills = "";
$exps = "";
$ratings = "";
while ($row = mysqli_fetch_assoc($dbc)) {
if (!empty($row['skill']) || !empty($row['exp']) || !empty($row['rating'])) {
if (! empty($row['skill'])) {
$skills .='<div class="s">';
$skills .= '<p>' , htmlspecialchars($row['skill']) , '</p>';
}
if (! empty($row['exp'])) {
$exps .= '<div class="s">';
$exps .= '<p>' , htmlspecialchars($row['exp']) , '</p>';
}
if (! empty($row['rating'])) {
$ratings .= '<div class="s">';
$ratings .= '<p>' , htmlspecialchars($row['rating']) , '</p>';
}
}
}
echo '<div id="con">';
if($skills){
echo '<h2 id="s">Skills</h2>';
echo $skills;
}
if($exps){
echo '<h2 id="exp">Exp</h2>';
echo $exps;
}
if($ratings){
echo '<h2 id="r">Rating</h2>';
echo $ratings;
}
echo '</div>';