While loop only executing once - php

I have a form that displays contact email addresses in text boxes, and drop down selections for titles for those corresponding emails.
TitleSelect1 Email1
TitleSelect2 Email2 ....
the emails have a title_id set, and the select list selects the existing Title. This works fine for the first contact, but the rest will only display the email address, the title dropdown is empty.
<?php
while ($row2 = mysql_fetch_array($Contact_list)) {
?>
<tr>
<td align="right"><select id="Contacts_title" name="Contacts_title[]">
<?
while ($row3 = mysql_fetch_array($title_list)) { //put the contact titles into an array
if ($row3['title_id'] == $row2['title_id']) {
?>
<option value="<? echo $row3['title_id'] ?>" selected="true"><? echo $row3['title'] ?>!</option>';
<?
}
else {
?>
<option value="<? echo $row3['title_id'] ?>"><? echo $row3['title'] ?> </option>';
<?
}
}
?>
</select>
</td>
<td align="left"><input type="text" id="Contacts" name="Contacts[]" value="<? echo $row2['email'] ?>"/></td>
</tr>
<?
$count++;
}

mysql_fetch_array() only goes through the results of a given query once. Since you're not executing the title_list query every time though your contact list loop, it's still at the end of the query results when you start every iteration after the first.
What you need to do is take all the results from your title_list query, put them into an array, and iterate over that for each of your contacts.
Here's a general example of how you'd do this (with extraneous bits trimmed out):
$contact_list = //some query
$title_list = //some query
$titles = array();
while($title_ar = mysql_fetch_array($title_list)) {
$titles[] = $title_ar;
}
while($contact_ar = mysql_fetch_array($contact_list)) {
// some stuff
foreach($titles as $title) {
// do something with each title
}
}

you should put the rows in a variable and echo that after the while loop.

once the inner while loop executes once fully, you wont get any more values in that mysql_fetch_array call again. Since the cursor reached the end of rows.
You should store the results of the inner while loop into a php array and then iterate through this array every time within the inner while loop.

Related

PHP dropdown menu that concatenates 2 rows from MySQL data table

Not experienced with creating forms in PHP.
I can get my form to produce a dropdown list that has one of my rows listed as an option, but as soon as I try to concatenate 2 rows together (from the same table) for option output...
a) It just doesn't work and I get errors
b) I get the first row as a single option, then my next row as a separate option.
I know there is a simple solution to this, but I am an online student just learning, and I can't seem to find a good example of the code to write it. I'm pretty sure it's an issue of quotes not being placed correctly.
MySQLTable Data:
Table Name: courses
Table Rows: course_id, course_name, max_enrolment
Sample Data: LO-COMP-8001, Intro to HTML, 20
function select_course(){
global $open;
$select = "SELECT * FROM courses";
$result = mysqli_query($open, $select);
return $result;
}
<form action="insert.php" method="post">
<dl>
<dt>Select Course</dt>
<dd><select name="course_id">
<?php // CREATE dropdown menu
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {
foreach ($row as $selection) {
echo "<option value=\"$selection\">$selection</option>";
}}
?>
</select>
</dd>
</dl>
Then there are a few more form fields such as student name and student id afterwards...
Goal Output:
course_id course-name
"LO-COMP-8001 Intro to HTML" ... as a single connected dropdown option and other remaining courses in a dropdown menu
Current Output:
LO-COMP-8001 (as an option)
Intro to HTML (as another option! ... No good)
20 (must be hidden, I need to check if course is full in another function and either allow or deny a student to enrolled etc.)
I have tried:
// output is the one mentioned above..
echo "<option value=\"$selection\">$selection</option>";
// or alternatively...
echo '<option value="'.$row['course_id'].'">'.$row['course_id'].'</option>';
But the second option creates all kinds of weird results.
This is what I am experimenting with right now...
echo '<option value="'.$row['course_id'] $row['course_name']'">'.$row['course_id'] $row['course_name'].'</option>';
But there is a bunch of issues with quotes and square brackets, and I just don't know how to format it correctly for the output.
Any assistance is appreciated.
$row holds the entire row as an associative array therefore no need for the 'foreach' loop.
function select_course(){
global $open;
$select = "SELECT * FROM courses";
$result = mysqli_query($open, $select);
return $result;
}
<form action="insert.php" method="post">
<dl>
<dt>Select Course</dt>
<dd><select name="course_id">
<?php // CREATE dropdown menu
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {?>
<option value="<?php echo $row["course_id"]; ?>"><?php echo $row["course_name"]; ?></option>
<?php }
?>
</select>
</dd>
</dl>
</form>
I was able to come up with another solution as well:
Once the foreach loop was removed, I tried cleaning up the code some... I'm not sure if this is uncommon or 'bad' style, but it does work.
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {
$course_id = $row['course_id'];
$course_name = $row['course_name'];
echo "<option value=\"$course_id\">$course_id $course_name</option>";
Results in: LO-COMP-8001 Intro to HTML as a single option, plus all my other courses in the database.

How to delete duplicate value from drop down list

I have the following coding with the values in drop down list and I would like to delete the duplicated value from the list but I don't know how to do??
<select id="dept" name="dept" class="dept" width="100" style="width: 100px">
<?php
while ($line = odbc_fetch_array($result)){
$fullNames=substr($line['fullName'],strpos($line['fullName'],'-')+1);
if ($fullNames==$_POST['dept']){
$selected="selected=\"selected\"";
}
else {
$selected="";
}
echo "<option value=\"".$fullNames."\" $selected>".$fullNames."</option>";
}
?>
</select>
Existing result in $_POST['dept']
AC
HR
AC
Admin
MIS
MIS
Expecting result in $_POST['dept']
AC
Admin
HR
MIS
I have modified your script
<select id="dept" name="dept" class="dept" width="100" style="width: 100px">
<?php
$dropdown = array();
while ($line = odbc_fetch_array($result)){
$fullNames=substr($line['fullName'],strpos($line['fullName'],'-')+1);
$selected="";
if($fullNames==$_POST['dept'])
$selected="selected=\"selected\"";
}
$dropdown[$fullNames] = "<option value=\"".$fullNames."\" $selected>".$fullNames."</option>";
}
echo implode('',$dropdown);
?>
</select>
you can also fetch unique records in your query as you didn't posted query and updatiing your provided code.
Use DISTINCT on your SQL statement to get the unique result.
Example:
SELECT DISTINCT col FROM Table
You can read the details about SQL DISTINCT here : https://www.w3resource.com/sql/select-statement/queries-with-distinct-multiple-columns.php
Since it's in an array you can use
$array = array_unique($array);
this will automatically detect any duplicates and remove them leaving only the first instance in the array, see https://www.php.net/manual/en/function.array-unique.php
EDIT: I'm not 100% sure if I understand how your data is coming in, but if I am understanding it correctly you can try this:
<select id="dept" name="dept" class="dept" width="100" style="width: 100px">
<?php
$fullNames = array();
while ($line = odbc_fetch_array($result)){
$fullNames=substr($line['fullName'],strpos($line['fullName'],'-')+1);
}
$fullNames = array_unique($fullNames);
if ($fullNames==$_POST['dept']){
$selected="selected=\"selected\"";
} else {
$selected="";
}
echo "<option value=\"".$fullNames."\" $selected>".$fullNames."</option>";
}
?>
</select>
That said you probably don't want to be directly using $_POST['dept'] but rather will want to do some validation first on $_POST['dept'] then once you confirm it's a valid value then use it in a variable like this:
$dept = $_POST['dept'];
Then you would need to update the other code to use $dept rather than $_POST['dept']. But this will prevent any unintended consequences from a user submitting an invalid or worse yet a intentionally malformed dept. It is good practice to never trust or directly use user input but always test and validate it.
Maybe you can push names into an array with the current loop then filter out the duplicated values. Then use another loop to echo the tag.
<select id="dept" name="dept" class="dept" width="100" style="width: 100px">
<?php
$array = [];
while ($line = odbc_fetch_array($result)){
$fullNames=substr($line['fullName'],strpos($line['fullName'],'-')+1);
array_push($array,$fullNames);//push all names into a array
}
$array = array_unique($array); //filter the duplicate names.
//another loop to echo the <option>
foreach ($array as $fullNames) {
if ($fullNames==$_POST['dept']){
$selected="selected=\"selected\"";
}
else {
$selected="";
}
echo "<option value=\"".$fullNames."\" $selected>".$fullNames."</option>";
}
?>
</select>

Row within a row with JSON

I have a webpage where it shows the lists of Projects and the monitoring of its progress/finances for every quarter. As shown below:
As you can see, my table is comprises of Project Name and a lists of sub-title's underneath it. And a series of columns per each quarter. Thru PHP I was able to populate the list of sub-titles under the Project Name, which also being fetched from the server side. Here's the code:
$sql = mysqli_query($con," My SELECT Statement ");
$i=0;
while($row = mysqli_fetch_assoc($sql)){
$ptitle = $row['Title'];
$iname = $row['Item'];
if($i%1)
{
?>
<?php } else { ?>
<tr>
<?php } ?>
<td width="25%"><?php echo $ptitle; ?></td>
<td></td>
</tr>
<tr>
<td><?php echo "<ul style='list-style-type: none;'><li>".nl2br($iname)."</li></ul>"; ?></td>
<td contenteditable="true" name="v1"></td>
Note: ptitle = ProjectName and iname = Semi-title underneath the Project's name.
Now, as you can see, the Project Name column literally "conquer" a single row on the left. Yet, the rows under the column of each quarter, should have its own separately, and must be parallel to the every sub-title underneath the Project Name. (Please refer to the image above for this) the only problem am encountering is... how can I make an editable row from inside a row, without affecting mysqli result? coz basically my table right now is kinda look like this:
Anyone who's more experience on this? I need your help.
PS: ...and oh! You might be wondering why do I include JSON in the title? It is because, I originally use JSON for editing those table rows before I even use mysqli_fetch_array. But when I include the results of the array inside the <table> tag, everything's changed and JSON is no longer working. So as of now, I am force to do it manually, meaning typing each <td contenteditable=true> in all of those rows. Yet, its not the desired output since I need another row within an existing row. Ideas? Anyone?
Figure Two:
Figure Three:
Count the number of lines in $iname, and then use a loop to create that many rows of contenteditable cells. You can also use this in the rowspan attribute of the <td> containing the title and subtitles.
$rows = substr_count($iname, "\n") + 1;
for ($i = 0; $i < $rows; $i++) {
echo "<tr>";
if ($i == 0) { ?>
<td rowspan='<?php echo $rows;?>' width='25%'><?php echo $ptitle . "<br>" . nl2br($iname);?></td>
<?php }
?>
<td contenteditable="true" name="v1"></td><td contenteditable="true" name="v2"></td>...
</tr>
<?php }
DEMO

Putting only selected checkboxes in a PhP variable, then displaying that variable underneath

I want to get selected values (of which multiple selections are possible) from my database generated dropdown menu and store those into a PhP variable. I then wish to display the content of that variable into a simple div element below.
This is my code so far which results in nothing inside my simple div:
<form id="menu1" method="POST">
<h2>Area Code</h2>
<select id="multi-select1" name="multi_select1" multiple="multiple">
<?php
//The query asking from our database
$areaCodeSQL = "SELECT ac.Number AS `AreaCode`, ac.Name AS `AreaName`
FROM `AreaCodes` ac"; //SQL query: From the table 'AreaCodes' select 'Number' and put into 'AreaCode', select Name and put into 'AreaName'
$areaCodeResults = $conn->query($areaCodeSQL); // put results of SQL query into this variable
if ($areaCodeResults->num_rows > 0) { // if num_rows(from $results) is greater than 0, then do this:
// output data of each row
foreach($areaCodeResults as $areaCodeResult) //for each item in $areCodeResults do this:
{
$areaNameAndCode = $areaCodeResult['AreaCode'] ." ". $areaCodeResult['AreaName']; //get AreaCode and AreaName from query result and concat them
$areaName = $areaCodeResult['AreaName']; // get AreaName
$areaCode = $areaCodeResult['AreaCode']; //get AreaCode
?><option class="menuoption1" name="menuAreaCode" value="<?php echo $areaCode ?>" ><?php echo $areaNameAndCode; ?></option><?php //Create this option element populated with query result variables
}
}
$result = $_POST['multi_select1'];
?>
</select>
</form>
<div id="showResults1"><?php echo $result ?></div>
Looking around online suggests I might need to use AJAX and jQuery but my tutor buddy insists this can be done within this one script. But I have no idea why my attempt does not work, can some one point me in the right direction???? :-)

Looping with while and foreach in PHP

I cannot seem to get foreach to work. Maybe I do not understand it correctly.
Here is my code:
$statement = "SELECT * FROM categories ORDER BY name ASC";
$query = mysql_query($statement)
...
...
$cals = array("sports","general","other","clubs");
foreach ($cals as $value)
{
/* echo "<h3>".$value."</h3>";
*/ echo "<table width='100%'>";
while ($array = mysql_fetch_array($query))
{
if ($array['calendar'] == $value)
{?>
<tr>
<td><?php echo $array['name']; ?></td>
<td><a onclick="update_form('<?php echo $array['name']; ?>', '<?php echo $array['calendar']; ?>')" href="#">Edit</a></td>
</tr>
<?php }
}
echo "</table><br />Value: $value";
}
The goal of this is to have the foreach change the if statement. I had planned for the if statement to say: if ($array['calendar'] == "sports") the first time, if ($array['calendar'] == "general") the second time, and so on. However, it shows all of the tables (in the source code), but no table rows are created after the first for each array value. For example, I correctly see the sports table, but I do not see any table rows for general, other, or clubs. There are records in that database that should appear in each of those. Could it be a problem with the while and if statements? If I manually set the $value in the if statement to one of the values in the array, it shows the correct records.
What am I missing?
Sample Data:
in the MySQL database -
categories table.
fields:
id
name
num_events
calendar
calendar_url
All of these fields except the calendar field has dummy data in it.
Currently, I have 5 records in there. Each one has a different calendar value. One is sports, one is clubs, and one is general. Depending on what value I place first in the array, it only shows that one table, of all of the values with whatever the first value in the array is.
Here is the source code from the resulting page:
<table width='100%'><tr>
<td>test4</td>
<td><a onclick="update_form('test4', 'sports')" href="#">Edit</a></td>
</tr>
<tr>
<td>test5</td>
<td><a onclick="update_form('test5', 'sports')" href="#">Edit</a></td>
</tr>
</table><br />Value: sports<table width='100%'></table><br />Value: general<table width='100%'></table><br />Value: other<table width='100%'></table><br />Value: clubs
As jcubic and timdev pointed out, there are a couple problems with the code as written. However, the algorithm you're trying to use is very inefficient because it loops over the entire result set for every calendar type. Instead, you can use a multi-column sort in SQL to do it in one pass:
$query = "SELECT * FROM categories ORDER BY calendar, name";
$results = mysql_query($results)
...
...
$last_cal = '';
while ($array = mysql_fetch_assoc($query))
{
if (!$last_cal) {
echo '<table>';
}
else if ($array['calendar'] != $last_cal) {
echo '</table>';
echo '<table>';
}
?>
....HTML for table row...
<?php
$last_cal = $array['calendar'];
}
First, just a point of style. You might consider renaming your variable $query to something like $results. It's holding the result of a query, not a query itself.
The problem is that you're not resetting $results. After the first table, you've iterated all the way through the array. When you get to the end, and there are no more rows to iterate over, mysql_fetch_assoc() returns false.
So try this:
foreach ($cals as $value)
{
while ($array = mysql_fetch_array($query))
{
if ($array['calendar'] == $value)
{
?>
<tr>
<td><?php echo $array['name']; ?></td>
<td><a onclick="update_form('<?php echo $array['name']; ?>', '<?php echo $array['calendar']; ?>')" href="#">Edit</a></td>
</tr>
<?php
}
}
echo "</table><br />Value: $value";
mysql_data_seek($query,0); // <=== Set the resultsets internal pointer back to zero (the first record).
}
The important bit is the mysql_data_seek() on the second to last line.
You could also stick that mysql_data_seek() right before the while() line, if you prefer. You just need to make sure that for each iteration of the foreach loop, the array pointer is reset before you hit while().
EDIT: s/reset/mysql_data_seek/
Try this instead...
$result = mysql_query($query);
while ($array = mysql_fetch_array($result)) {
...
}
mysql_fetch_array return array indexed by integer if you want asoc array change
while ($array = mysql_fetch_array($query))
to this
while ($array = mysql_fetch_assoc($query))

Categories