Nested while loop is only running once - php

I'm running two while loops to display a table in html.
The first while loop is to display data from a selected databasetable as long as there is content in the database.
My second while loop displays a dropdown, where the content of another table should be displayed.
My goal is to show this dropdown each row. My problem is that the dropdown filled with data is just shown in the first tablerow. All the other rows just show an empty selectfield. Can someone help me what I did wrong?
My Code so far:
$link=pg_connect($conn_str);
if (!$link) {die('Verbindung schlug fehl.');}
$arbeitspaket = pg_query($link, "SELECT * FROM arbeitspaket WHERE id='$_SESSION[user_id]'");
$sql = "SELECT * FROM anwender ORDER BY nachname ASC";
$mitarbeiter = pg_query($link, $sql); ?>
<form action=mitarbeiterauswahl.php method=post>
<table border=1>
<tr>
<th>Arbeitspaket-ID</th>
<th>Arbeitspaketbezeichnung</th>
<th>Mitarbeiterbedarf</th>
<th>Mitarbeiterzuordnung</th>
</tr>
<?php while($results=pg_fetch_array($arbeitspaket)){?>
<tr>
<td><?php echo $results['apid']; ?></td>
<td><?php echo $results['arbeitspaketbezeichnung']; ?></td>
<td><?php echo $results['mitarbeiterbedarf']; ?></td>
<td>
<select name="mitarbeiter">
<?php while($row = pg_fetch_array($mitarbeiter)){
echo '<option value="'. $row['id'] .'">('. $row['id'] .') '. $row['vorname'] .' '. $row['nachname'] .'</option>'."\n"; }?>
</select>
</td>
</tr>
<?php } ?>
</table>
</form>

Why don't you try a foreach? Looks much better in this situation. Something like this:
<table border=1>
<tr>
<th>Arbeitspaket-ID</th>
<th>Arbeitspaketbezeichnung</th>
<th>Mitarbeiterbedarf</th>
<th>Mitarbeiterzuordnung</th>
</tr>
<?php $results= pg_fetch_array($arbeitspaket);
$arbeiters = pg_fetch_array($mitarbeiter);
foreach($results as $result){?>
<tr>
<td><?php echo $result['apid']; ?></td>
<td><?php echo $result['arbeitspaketbezeichnung']; ?></td>
<td><?php echo $result['mitarbeiterbedarf']; ?></td>
<td>
<select name="mitarbeiter">
<?php foreach($arbeiters as $arbeiter) {
echo '<option value="'. $arbeiter) ['id'] .'">('. $arbeiter) ['id'] .') '. $arbeiter) ['vorname'] .' '. $arbeiter) ['nachname'] .'</option>'."\n"; }?>
</select>
</td>
</tr>
<?php } ?>
</table>

The problem in your code is that you consume all the data in the first loop, after that it is gone. Store the data in an array and iterate over the array.
<form action=mitarbeiterauswahl.php method=post>
<table border=1>
<tr>
<th>Arbeitspaket-ID</th>
<th>Arbeitspaketbezeichnung</th>
<th>Mitarbeiterbedarf</th>
<th>Mitarbeiterzuordnung</th>
</tr>
<?php
$mitarbeiter_array = array();
while($row = pg_fetch_array($mitarbeiter)) {
$mitarbeiter_array[] = $row;
}
unset($row);
?>
<?php while($results=pg_fetch_array($arbeitspaket)){?>
<tr>
<td><?php echo $results['apid']; ?></td>
<td><?php echo $results['arbeitspaketbezeichnung']; ?></td>
<td><?php echo $results['mitarbeiterbedarf']; ?></td>
<td>
<select name="mitarbeiter">
<?php foreach($mitarbeiter_array as $row){
echo '<option value="'. $row['id'] .'">('. $row['id'] .') '. $row['vorname'] .' '. $row['nachname'] .'</option>'."\n"; }?>
</select>
</td>
</tr>
<?php } ?>
</table>
</form>

i think it will be better way and will be fast
<form action=mitarbeiterauswahl.php method=post>
<?php
$select_html = '<select name="mitarbeiter">';
$select_list_data = pg_fetch_array($mitarbeiter);
?>
<?php foreach($select_list_data as $row){ ?>
<?php
$select_html .= '<option value="'. $row['id'] .'">('. $row['id'] .') '. $row['vorname'] .' '. $row['nachname'] .'</option>';
?>
<?php } ?>
<?php $select_html .= '</select>'; ?>
<table border=1>
<tr>
<th>Arbeitspaket-ID</th>
<th>Arbeitspaketbezeichnung</th>
<th>Mitarbeiterbedarf</th>
<th>Mitarbeiterzuordnung</th>
</tr>
<?php
$fetch_results = pg_fetch_array($arbeitspaket);
foreach($fetch_results as $results){ ?>
<tr>
<td><?php echo $results['apid']; ?></td>
<td><?php echo $results['arbeitspaketbezeichnung']; ?></td>
<td><?php echo $results['mitarbeiterbedarf']; ?></td>
<td>
<?php echo $select_html; ?>
</td>
</tr>
<?php } ?>
</table>

Related

Using PHP to get data from MSQL and need a button in the foreach table

Let me post some code first so I can explain more of what I want to accomplish.
<?php
require "../config.php";
require "../common.php";
if (isset($_POST['submit'])) {
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'])) die();
try {
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT * FROM saledata WHERE itemnumber = :itemnumber";
$itemnumber = $_POST['itemnumber'];
$statement = $connection->prepare($sql);
$statement->bindParam(':itemnumber', $itemnumber, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>
<?php require "templates/header.php"; ?>
<?php
if (isset($_POST['submit'])) {
if ($result && $statement->rowCount() > 0) { ?>
<h2>Results</h2>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<table>
<thead>
<tr>
<th>Item Number</th>
<th>Sale Number</th>
<th>Lot Number</th>
<th>Item Description</th>
<th>Seller Number</th>
<th>Buyer Number</th>
<th>Sold</th>
<th>Sold</th>
<th>Paid</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) : ?>
<tr>
<td><?php echo escape($row["itemnumber"]); ?></td>
<td><?php echo escape($row["salenumber"]); ?></td>
<td><?php echo escape($row["lotnumber"]); ?></td>
<td><?php echo escape($row["itemdescription"]); ?></td>
<td><?php echo escape($row["sellernumber"]); ?></td>
<td><?php echo escape($row["buyernumber"]); ?></td>
<td><?php echo escape($row["sold"]); ?></td>
<td><?php echo escape($row["paid"]); ?></td>
<td><?php echo escape($row["amount"]); ?></td>
<td><?php echo escape($row["date"]); ?> </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php } else { ?>
<blockquote>No results found for <?php echo escape($_POST['itemnumber']); ?>.</blockquote>
<?php }
} ?>
<h2>Find item based on Item Number</h2>
<form method="post">
<input name="csrf" type="hidden" value="<?php echo escape($_SESSION['csrf']); ?>">
<label for="itemnumber">Item Number</label>
<input type="text" id="itemnumber" name="itemnumber"><br><br>
<input type="submit" name="submit" value="View Results">
</form>
<?php require "templates/footer.php"; ?>
(END)
This produces an HTML table containing the data in the database in rows. What I would like is a button at the beginning or end of the rows that will modify a field in that item's row. An example is the column for sold or not sold. What I would like is a button at either the beginning or the end of each row that modifies the "sold" column from N to Y for that item. I have tried to put a block of code in the code here at the end but I can't get it to do anything. I can get the button to show using the HTML tag but can't get it to actually do anything.
Here is the concept of the foreach:
<td><?php echo escape($row["sold"]); ?></td>
<td><?php echo escape($row["paid"]); ?></td>
<td><?php echo escape($row["amount"]); ?></td>
<td><?php echo escape($row["date"]); ?> </td>
<td>BUTTON and code to change Sold from N to Y</td>
</tr>
Any assistance would be greatly appreciated!
I know my stuff is probably elementary and not very efficient, but I have been working on this project for several weeks and never worked with a MYSQL database before.

PHP how to delete a specific row from database with html table button

I am trying to delete a specific entry from the database with a button. I know this has already been asked several times, unfortunately the solutions don't really work for me. The goal would be, if I click on the button in the 3rd row, that this line is deleted. I have the problem that I always only delete the last ids or all ids at once.
Maybe someone can help me, thank you.
admin.php
<?php
include('connection.php');
include('read.php');
?>
<form action="admin.php" method="post">
<div class="table-wrapper">
<div class="table-scroll">
<table id="myTable">
<tr>
<th>ID</th>
<th>Kartentyp</th>
<th>Absender</th>
<th>Empfänger</th>
<th>Sendedatum</th>
<th id="smallCol">Verschickt</th>
<th id="smallCol">Bestätigung</th>
<th>Edit</th>
</tr>
<?php
foreach ($result as $row) {
if ($row['Dispatched'] == 0) {
$dispatched = 'Pending';
} else {
$dispatched = 'Versendet';
}
?>
<tr class="Alle <?php echo $row['Category']; ?> <?php echo $row['Dispatched']; ?>">
<td><?php echo $row['ID']; ?></td>
<td><?php echo $row['Category']; ?></td>
<td><?php echo $row['Sender']; ?></td>
<td><?php echo $row['Receiver']; ?></td>
<td><?php echo $row['SendDate']; ?></td>
<td><?php echo $dispatched; ?></td>
<td>Placeholder</td>
<td><input type="submit" name="delete" value="delete" >
<button data-target="modal1" class="modal-trigger">Modal</button>
</td>
</tr>
<?php
}
if (isset($_POST['delete'])) {
echo $row['ID'];
$deleteQuery = "DELETE FROM card WHERE id = " . $row['ID'];
$statement = $pdo->prepare($deleteQuery);
$statement->execute();
}
?>
</table>
</div>
</div>
</form>
read.php
<?php
include('connection.php');
$statement = $pdo->prepare("SELECT * FROM card ORDER BY ID ASC");
$statement->execute();
$result = $statement->fetchAll();
if ($statement->rowCount() > 0) {
foreach ($statement->fetchAll() as $row) {
$id = $row['ID'];
$imagePath = $row["ImagePath"];
$sender = $row["Sender"];
$senderEmail = $row["SenderEmail"];
$receiver = $row["Receiver"];
$receiverEmail = $row["ReceiverEmail"];
$subject = $row["Subject"];
$text = $row["Text"];
$sendDate = $row["SendDate"];
$dispatched = $row["Dispatched"];
$category = $row['Category'];
}
}
?>
You can archive this by using get request without posting whole data to server.
if( !empty($_GET['id']) ){
$deleteQuery = "DELETE FROM card WHERE id = " . $id_to_delete;
$statement = $pdo->prepare($deleteQuery);
$statement->execute();
header('location:youfilename.php');
exit;
}
?>
<div class="table-wrapper">
<div class="table-scroll">
<table id="myTable">
<tr>
<th>ID</th>
<th>Kartentyp</th>
<th>Absender</th>
<th>Empfänger</th>
<th>Sendedatum</th>
<th id="smallCol">Verschickt</th>
<th id="smallCol">Bestätigung</th>
<th>Edit</th>
</tr>
<?php
foreach ($result as $row) {
if ($row['Dispatched'] == 0) {
$dispatched = 'Pending';
} else {
$dispatched = 'Versendet';
}
?>
<tr class="Alle <?php echo $row['Category']; ?> <?php echo $row['Dispatched']; ?>">
<td><?php echo $row['ID']; ?></td>
<td><?php echo $row['Category']; ?></td>
<td><?php echo $row['Sender']; ?></td>
<td><?php echo $row['Receiver']; ?></td>
<td><?php echo $row['SendDate']; ?></td>
<td><?php echo $dispatched; ?></td>
<td>Placeholder</td>
<td>Delete
<button data-target="modal1" class="modal-trigger">Modal</button>
</td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</form>
You can modify your code like that :
<?php
include('connection.php');
include('read.php');
if( !empty($_POST) ){
foreach( $_POST as $key_post => $value_post ){
if (preg_match('/delete_/i',$key_post) ) {
$id_to_delete = (integer) str_replace('delete_','', $key_post);
$deleteQuery = "DELETE FROM card WHERE id = " . $id_to_delete;
$statement = $pdo->prepare($deleteQuery);
$statement->execute();
}
}
}
?>
<form action="admin.php" method="post">
<div class="table-wrapper">
<div class="table-scroll">
<table id="myTable">
<tr>
<th>ID</th>
<th>Kartentyp</th>
<th>Absender</th>
<th>Empfänger</th>
<th>Sendedatum</th>
<th id="smallCol">Verschickt</th>
<th id="smallCol">Bestätigung</th>
<th>Edit</th>
</tr>
<?php
foreach ($result as $row) {
if ($row['Dispatched'] == 0) {
$dispatched = 'Pending';
} else {
$dispatched = 'Versendet';
}
?>
<tr class="Alle <?php echo $row['Category']; ?> <?php echo $row['Dispatched']; ?>">
<td><?php echo $row['ID']; ?></td>
<td><?php echo $row['Category']; ?></td>
<td><?php echo $row['Sender']; ?></td>
<td><?php echo $row['Receiver']; ?></td>
<td><?php echo $row['SendDate']; ?></td>
<td><?php echo $dispatched; ?></td>
<td>Placeholder</td>
<td><input type="submit" name="delete_<?php echo $row['ID']; ?>" value="delete" >
<button data-target="modal1" class="modal-trigger">Modal</button>
</td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</form>
Your error was you don't used the POST value to delete the row but the last ID store in the row variable that come from your query reading.
Becarfull too you make a wrong usage of the prepare function in PDO.

Having issues sorting with links in PHP

So, I am trying to sort a database by clickable links. I have a function that is supposed to order them, but for some reason it isn't working. Also, once I add something to the database and submit, if I click on the links to order, it sends me to my actual function holding file in the url, which is weird.
Forgive table formatting issues. I'm still debugging that.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Project 1</title>
</head>
<body>
<h1 style='text-align:center;'>Movie Collection Database</h1>
<form method='post' action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table align='center' border='1' cellpadding='5'>
<tr>
<td>
<input type="text" size='40' name="movieTitle" value="Movie Title">
</td>
<td>
<input type="text" name="studioName" value="Studio Name">
</td>
<td>
<select name="movieRating">
<option value="G">G</option>
<option value="PG">PG</option>
<option value="PG-13">PG-13</option>
<option value="R">R</option>
<option value="NC-17">NC-17</option>
<option value="Not Rated">Not Rated</option>
</select>
</td>
<td>
<input type="text" name="publicationYear" value="2015">
</td>
<td>
<input type="number" name="imdbRating" value="10.0">
</td>
<td>
<input type="number" name="runTime" value="0">
</td>
<td>
<input type="checkbox" name="add">Add
</td>
</tr>
</table>
<?php
$db = new PDO("mysql:host=localhost;dbname=berkleyr", "berkleyr", "12345");
?>
<?php include_once("Project1DB.php"); ?>
<?php if ($_SERVER['REQUEST_METHOD'] === "POST"):
delete($db);
if(isset($_POST['add']))
{
try
{
Insert($db, $_POST['movieTitle'], $_POST['studioName'], $_POST['movieRating'], $_POST['publicationYear'], $_POST['imdbRating'], $_POST['runTime']);
}
catch (PDOException $error)
{
$db->rollback();
echo "Bad things Happened";
$db = null;
die("Connection failed: " . $error->getMessage());
}
}
?>
<table align='center' border='1'>
<tr>
<th>Title</th>
<th>Studio Name</th>
<th>Rating</th>
<th>Pub Year</th>
<th>IMDB Rating</th>
<th>Run Time</th>
<th>Delete</th>
</tr>
<?php foreach (Select($db) as $row): ?>
<tr>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['studio']; ?></td>
<td><?php echo $row['rating']; ?></td>
<td><?php echo $row['pub_year']; ?></td>
<td><?php echo $row['imdb_rating']; ?></td>
<td><?php echo $row['run_time']; ?></td>
<?php echo "<td><input type='checkbox' name='". $row['id'] . "' value='" . $row['id'] . "'></td>";?>
</tr>
<?php endforeach ?>
<?php
if (isset($db))
{
$db = null; // make sure an exception didn't already close the connection. If not, close it now.
}
?>
<?php else: ?>
<table align='center' border="1">
<tr>
<th>Title</th>
<th>Studio Name</th>
<th>Rating</th>
<th>Pub Year</th>
<th>IMDB Rating</th>
<th>Run Time</th>
<th>Delete</th>
</tr>
<?php foreach (Select($db) as $row): ?>
<tr>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['studio']; ?></td>
<td><?php echo $row['rating']; ?></td>
<td><?php echo $row['pub_year']; ?></td>
<td><?php echo $row['imdb_rating']; ?></td>
<td><?php echo $row['run_time']; ?></td>
<?php echo "<td><input type='checkbox' name='". $row['id'] ."' value='" . $row['id'] . "'></td>";?>
</tr>
<?php endforeach ?>
<?php endif ?>
<td colspan="7" align="center">
<input type='submit' name='submit' value='Update Database' />
</td>
</table>
</form>
</body>
</html>
Here is my function for sorting:
function orderBy($order)
{
switch($order)
{
case "title":
$sorted = $this->db->prepare("SELECT * FROM movie ORDER BY movie.title ASC");
break;
case "studio":
$sorted = $this->db->prepare("SELECT * FROM movie ORDER BY movie.studio ASC");
break;
case "rating":
$sorted = $this->db->prepare("SELECT * FROM movie ORDER BY movie.rating ASC");
break;
case "pub_year":
$sorted = $this->db->prepare("SELECT * FROM movie ORDER BY movie.pub_year ASC");
break;
case "imdb_rating":
$sorted = $this->db->prepare("SELECT * FROM movie ORDER BY movie.imdb_rating ASC");
break;
case "run_time":
$sorted = $this->db->prepare("SELECT * FROM movie ORDER BY movie.run_time ASC");
break;
}
$sorted->execute();
}

Multiple SELECT variables are not displaying

Having issues displaying all of the selected data entries inside SELECT. Right now the only one that is displaying is the recipe_direct data. Each table data should list in one row the name, ingred, direct, auth name and auth email.
<div class="starter-template">
<h1>Recipes</h1>
</div>
<?php
try
{
$sql = 'SELECT recipe_id, recipe_name, recipe_ingred, recipe_direct, author_name, author_email FROM recipes';
$result = $pdo->query($sql);
}
catch (PDOException $e)
{
$error = 'Error fetching recipes: ' . $e->getMessage();
}
while ($row = $result->fetch())
{
$recipes[$row['recipe_id']] = $row;
}
?>
<p>Add a Recipe</p>
<?php foreach ($recipes as $id => $recipe): ?>
<blockquote>
<table class="table table-striped">
<tr>
<td><?php echo $recipe['recipe_name']; ?></td>
<td><?php echo $recipe['recipe_ingred']; ?></td>
<td><?php echo $recipe['recipe_direct']; ?></td>
<td><?php echo $recipe['author_name']; ?></td>
<td><?php echo $recipe['author_email']; ?></td>
</tr>
<?php htmlout($recipe_html); ?> |
edit |
delete
</table>
</blockquote>
<?php endforeach; ?>
You overwrite $recipe_html each time you assign a value to it
why not just echo out the table rows:
<table>
<?php foreach ($recipes as $id => $recipe): ?>
<tr>
<td><?= $recipe['recipe_name']; ?></td>
<td><?= $recipe['recipe_ingred']; ?></td>
<td><?= $recipe['recipe_direct']; ?></td>
<td><?= $recipe['author_name']; ?></td>
<td><?= $recipe['author_email']; ?></td>
</tr>
<?php endforeach; ?>
</table>
EdIt as #Fred -ii- states, the table tags should be outside the loop
Everything looks correct up until your foreach.
<blockquote>
<table class="table table-striped">
<?php foreach ($recipes as $id => $recipe): ?>
<tr>
<td><?php $recipe_html = $recipe['recipe_name']; ?></td>
<td><?php $recipe_html = $recipe['recipe_ingred']; ?></td>
<td><?php $recipe_html = $recipe['recipe_direct']; ?></td>
<td><?php $recipe['author_name']; ?></td>
<td><?php $recipe['author_email']; ?></td>
</tr>
<p> //seems you were missing opening <p> tag//
<?php htmlout($recipe_html); ?> |
edit | //can use shorthand here//
delete //can use shorthand here//
</p>
<?php endforeach; ?>
</table>
</blockquote>

cant fetch row data from database after search in search form using codeigniter

hey guys i am new in codeigniter and i am working on an application in which i have database and many records in database..i make a search form in which i make a text field in which user can fill any field value and search records.but here is a small problem..when i fill a name in textbox and click on search button no record display on view . . pls help me . . thanks ..
my controller is:
function search()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('inputsearch', 'Search Your Text Here','required');
if ($this->form_validation->run() == TRUE)
{
$this->load->helper('form');
$this->load->helper('html');
$search_this=$this->input->post('inputsearch');
$this->load->model('mod_user');
$searchmember=$this->mod_user->search_member($search_this);
$data['searchmember'] = $searchmember;
var_dump($searchmember);
$this->load->view('view_home',$data);
$this->load->view('view_homemember',$data);
}
else
{
redirect('ctl_home');
}
}
view is:
<form class="userinfo" action="" method="post">
<table border="1" cellpadding="2" cellspacing="0">
<tr>
<td width="5%;"> </td>
<td width="5%;"> </td>
<td width="15%;">Name</td>
<td width="15%;">Moderator Name</td>
<td width="20%;">KCC Branch</td>
<td width="15%;">Father/Husband Name</td>
<td width="15%;">Address</td>
<td width="10%;">Date</td>
</tr>
<?php foreach ($rows as $row):?>
<tr>
<td><?php echo anchor("Ctl_Home/edit_member/" . $row->member_id, 'Edit'); ?></td>
<td>Delete</td>
<td><?php echo $row->member_name; ?></td>
<td><?php echo $row->moderator_name; ?></td>
<td><?php echo $row->branch_name; ?></td>
<td><?php echo $row->father_name; ?></td>
<td><?php echo $row->address; ?></td>
<td><?php echo $row->date; ?></td>
</tr>
<?php endforeach; ?>
</table>
</form>
my model is:
function search_member($search_this)
{
$query=$this->db->query("SELECT tbl_members.* , tbl_moderators.member_id AS moderator_id, tbl_moderators.member_name AS moderator_name, tbl_moderators.member_no AS moderator_no, tbl_branches.branch_name FROM tbl_members, tbl_members AS tbl_moderators, tbl_branches WHERE tbl_members.moderator_id = tbl_moderators.member_id AND tbl_branches.branch_id = tbl_members.kcc_branch
AND CONCAT(tbl_members.member_name, ' ', tbl_moderators.member_name, ' ',tbl_members.moderator_id, ' ', tbl_moderators.member_id, ' ',tbl_branches.branch_name, ' ',tbl_members.father_name, ' ',tbl_members.address, ' ',tbl_moderators.address, ' ',tbl_members.date, ' ',tbl_moderators.date) like '%".$search_this."%'");
if ($query->num_rows >= 0)
{
foreach($query->result_array() as $row)
{
$data[]=$row;
}
return $data;
}
}
Your loop should have been like this
<?php foreach ($searchmember as $row):?>
<tr>
<td><?php echo anchor("Ctl_Home/edit_member/" . $row->member_id, 'Edit'); ?></td>
<td>Delete</td>
<td><?php echo $row->member_name; ?></td>
<td><?php echo $row->moderator_name; ?></td>
<td><?php echo $row->branch_name; ?></td>
<td><?php echo $row->father_name; ?></td>
<td><?php echo $row->address; ?></td>
<td><?php echo $row->date; ?></td>
</tr>
<?php endforeach; ?>
It is $searchmember as $row instead of $rows as $row in foreach
If $data['searchmember'] contains value in controller,
you can access the varibale in view as $searchmember

Categories