I have a PHP page where its querying data from the database and putting it in a table. The first column is where I would like the user to assign a person to that row. I was able to do that successfully (the select in a loop) but now I'm having a problem when its getting pushed out to the other page.
Below is the first page:
$sql = "SELECT * FROM meetingDump WHERE Meeting_ID IN ($Series)";
$rs=odbc_exec($conn,$sql);
while($row = odbc_fetch_array($rs))
{
$ID = odbc_result($rs,"ID");
$Meeting_ID = odbc_result($rs,"Meeting_ID");
$Title = odbc_result($rs,"Title");
$StartTime = odbc_result($rs,"StartTime");
$EndTime = odbc_result($rs,"EndTime");
$Organizer = odbc_result($rs,"Organizer");
echo '<tr>
<td>';
{
$box1 = array();
$result1 = "SELECT FullName FROM User";
$rs1=odbc_exec($connu,$result1);
while($row = odbc_fetch_array($rs1)) { $box1[] = $row; }
}
/* Generate select box contents */
$AssignedTo = '<select name="AssignedTo[]" onchange="autoSubmit()">';
$AssignedTo .= '<option selected="selected">---< Select Engineer >---</option>';
if (!empty($box1)) {
foreach ($box1 as $k => $v) {
$AssignedTo .= '<option value="'.$v['FullName'].'">'.$v['FullName'].'</option>';
}
}
$AssignedTo .= '</select>';
/* Output */
echo $AssignedTo;
echo '
</td>
<input name="AssignedID[]" type="hidden" value="' . $ID . '" />
<td>' . $Meeting_ID . '</td>
<td>' . $Title . '</td>
<td>' . $StartTime . '</td>
<td>' . $EndTime . '</td>
<td>' . $Organizer . '</td>';
}
Now for the second page I currently have:
foreach($_POST['AssignedTo'] as $AssignedTo)
{
echo '<br>' . $AssignedTo;
}
That gets me all the selected names, which is perfect, but I'm trying to correlate the assignedTo field with the meeting_id field.
Any ideas?
UPDATE:
The comment from AeroX helped me figure it out!
$AssignedID = $_POST['AssignedID'];
$AssignedTo = $_POST['AssignedTo'];
foreach ($AssignedID as $Key => $value)
{
echo $AssignedID[$Key] .' '. $AssignedTo[$Key];
echo '<br>';
}
In your example, because of the way the POST variables $_POST['AssignedID'] and $_POST['AssignedTo'] will be populated you can just pull the Value from each Array where they both have matching Keys. This will then give you the related records.
Something like the below should work for you:
$AssignedID = $_POST['AssignedID'];
$AssignedTo = $_POST['AssignedTo'];
foreach(array_keys($AssignedID) as $Key)
{
echo $AssignedID[$Key];
echo $AssignedTo[$Key];
}
Related
I am wondering if anyone could help? I am trying to send 2 variables which I have extracted from a database to another page when the user clicks on a link. At the moment I can only send one. I know what I am doing below is wrong.....basically I want to send both uninum and groupid over to the other page.
for ($i = 0; $i < $count; $i++){
$q = "SELECT participants.sname, participants.uninum, groups.groupid FROM participants INNER JOIN groups ON participants.uninum =
groups.uninum WHERE groups.groupid ='".$groups[$i]."'";
$result = mysqli_query ($dbcon, $q); // Run the query.
if ($result) { // If it ran, display the records.
// Table header.
echo '<table>
<tr><td><b>Edit</b></td>
<td><b>Surnname</b></td>
<td><b>University ID</b></td>
<td><b>Group</b></td>
</tr>';
// Fetch and display the records:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<tr>
<td>Edit</td>
<td>' . $row['sname'] . '</td>
<td>' . $row['uninum'] . '</td>
<td>' . $row['groupid'] . '</td>
</tr>';
}
echo '</table>'; // Close the table.
mysqli_free_result ($result); // Free up the resources.
echo "<br><br>";
} else { // If it did not run OK.
// Public message:
echo '<p class="error">The current users could not be retrieved. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbcon) . '<br><br>Query: ' . $q . '</p>';
}
}
You have used ? instead of & in your code.
<td>Edit</td>
Should be:
<td>Edit</td>
You can try this :
Edit
At the moment I have the below script which auto generates the table names and row data automatically by looking at a sqlite table. So regardless of if you have 2 or 10 columns this script works.
At the moment the script outputs the results like this:
Output currently appears as a Row
I have tried altering the script so that it outputs the results like below. Can someone assist or guide me in the right direction to achieve this?
Is it possible to output the results of the query in the below format: going down in a column rather than across as a row ?
Output should appear as a Column
<?
$ED = $_GET['ED'];
$ID = $_GET['ID'];
$table_name = $_GET['table'];
?>
<table border="1">
<tr>
<td>
<table>
<?php // Display all sqlite column names for chosen table
$tablesquery = $db->query("PRAGMA table_info($table_name)");
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
if ($table['name'] == "ID") {
echo "<tr><td>" . $table['name'] . "</td></tr>";
} else {
$table_name_header = ucwords(strtolower(str_replace('_', ' ', $table['name'])));
echo "<tr><td>" . $table_name_header . "</td></tr>";
}
}
?>
</table>
</td>
<td>
<table>
<?
// Display all sqlite data for chosen table
$tablesquery = $db->query("PRAGMA table_info($table_name)");
$columns = array();
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
$columns[] = $table['name'];
}
// Display * from USERS
// $results = $db->query('SELECT * FROM ADMIN_LOGIN WHERE ID = "57"');
$results = $db->query('SELECT * FROM ' . $table_name . ' WHERE ID = "' . $ID . '"');
while ($row = $results->fetchArray()) {
// echo "<tr>";
$test = $row[0];
foreach ($columns as $col)
echo "<tr><td>" . $row[$col] . "</td></tr>";
}
// echo "</tr>";
?>
</table>
</td>
</tr>
</table>
Modifying the code to the below by putting the data into an combined array and then pulling it back via a loop it will display as required:
<?
// Display all sqlite data for chosen table
$tablesquery = $db->query("PRAGMA table_info($table_name)");
$columns = array();
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
$columns[] = $table['name'];
}
// Display * from USERS
// $results = $db->query('SELECT * FROM ADMIN_LOGIN WHERE ID = "57"');
$results = $db->query('SELECT * FROM ' . $table_name . ' WHERE ID = "' . $ID . '"');
while ($row = $results->fetchArray()) {
// echo "<tr>";
$test = $row[0];
foreach ($columns as $col)
$column_data[] = $row[$col];
// echo "<tr><td>" . $row[$col] . "</td></tr>";
}
// echo "</tr>";
?>
<?
$array = $columns;
$array2 = $column_data;
$result = array_combine($array, $array2);
//print_r($result);
?><br><br>
<center>
<table border="0" cellpadding="2" cellspacing="2" color="#4B708D">
<thead>
<?
foreach($result as $key => $value) {
echo "<tr><td bgcolor='#c6d5e1'>$key</td><td bgcolor='#FFFFFF'>$value</td></tr>";
}
?>
</thead>
</table>
I have a table in which the last cell is a bit value. When new data is inserted, the bit is automatically set to 1. I used PHP to display the contents of the table, in <table> form, wherein the last cell contains a checkbox. I didn't surround these checkboxes in <form></form> tags, they're just <input ... /> with name="stat[]." I used an array for the name so that PHP knows that $_POST['stat'] will be an array containing all the inputs.
One or more checkboxes can be checked and submitted to update the bit value to 0.
Questions:
Do I have to use <form> tags for this? The AJAX isn't working.
Can the <button> element be assigned a method and action?
HTML Button. Notice there is no form here.
<input type="submit" id="updateList" type="button" method="post" action="classes/requests/updateList.php" value="update list" />
jQuery and AJAX
$('input#updateList').on('click', function (e) {
e.preventDefault();
var open = 'yes';
if ($('.update:checked').length <= 0) {
$('.fade_bg').fadeIn(200);
$('#updateStat').slideDown(600);
$('span#stat2').fadeIn(400).text('You must make a selection');
$('a#closeBox2').show();
return false;
}
else {
$('.update').each(function (index) {
var chckd = $('#chck' + index).val();
open = 'no';
$.ajax ({
type: 'post',
url: 'classes/requests/updateList.php',
data: {
stat: chckd
},
success: function(data) {
if (data === 'updated') {
alert(data);
// $('.fade_bg').fadeIn(200);
// $('#reqStat').slideDown(600);
// $('span#stat').fadeIn(400).text('Thank you. Your request has been submitted.');
// $('a#successClose').show();
}
else {
$('span#stat').fadeIn(400).text('There was an error in submitting your request');
$('a#closeBox').show();
return false;
}
}
});
});
}
});
PHP for rendering the HTML list
include('../dbconnect.php');
$closed = 'no';
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare("SELECT RequestID, DateAdded, Graphic1Desc, Graphic2Desc, Graphic3Desc, ColorChart, Hex1, Hex2, Hex3, Hex4, Hex5, Hex6, Hex7, Hex8 FROM GraphicsRequest WHERE fulfilled = :done AND RequestID > 0");
print '<table id="pendingReqs">';
print '<tr id="headers">
<td>Date</td>
<td>Gr. 1</td>
<td>Gr. 2</td>
<td>Gr. 3</td>
<td>Colors?</td>
<td>HEX Vals 1-8</td>
<td>Done</td>
</tr>';
$stmt->bindParam(':done', $closed);
for ($r = 0; $r <= $stmt->rowCount(); $r++) {
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$id = $row[$r]['RequestID'];
$date = $row[$r]['DateAdded'];
$d1 = $row[$r]['Graphic1Desc'];
$d2 = $row[$r]['Graphic2Desc'];
$d3 = $row[$r]['Graphic3Desc'];
$chart = $row[$r]['ColorChart'];
$h1 = $row[$r]['Hex1'];
$h2 = $row[$r]['Hex2'];
$h3 = $row[$r]['Hex3'];
$h4 = $row[$r]['Hex4'];
$h5 = $row[$r]['Hex5'];
$h6 = $row[$r]['Hex6'];
$h7 = $row[$r]['Hex7'];
$h8 = $row[$r]['Hex8'];
print '<tr>
<td>' . $date . '</td>
<td class="desc">' . $d1 . '</td>
<td class="desc">' . $d2 . '</td>
<td class="desc">' . $d3 . '</td>
<td>' . $chart . '</td>
<td>'
. $h1 . ', '
. $h2 . ',<br />'
. $h3 . ', '
. $h4 . ',<br />'
. $h5 . ', '
. $h6 . ',<br />'
. $h7 . ', '
. $h8 . '<br /></td>
<td><input type="checkbox" class="update" name="stat[]" id="chk' . $id . '"/></td></tr>';
}
print '</table>';
print $id;
PHP for updating the list
function updateStatus() {
include('../../../dbconnect.php');
$updated = false;
$open = 'yes';
$id = 0;
try {
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stat = $pdo->prepare('SELECT RequestID FROM GraphicsRequest WHERE fulfilled = :open');
$stat->bindParam(':open', $open);
$_POST['stat'] = array();
for ($r = 0; $r <= $stat->rowCount(); $r++) {
$stat->execute();
$row = $stat->fetchAll(PDO::FETCH_ASSOC);
$id = $_POST['stat'][$row[$r]['RequestID']];
if (ISSET($_POST['stat[' . $id . ']'])) {
$open = 'no';
$stmt = $pdo->prepare('UPDATE GraphicsRequest SET fulfilled = :open');
$stmt->bindParam(':open', $open);
$stmt->execute();
$pdo = null;
if ($stmt->rowCount() == 0)
echo('rowCount = 0');
else
$updated = true;
return $updated;
}
}
}
catch (PDOException $err){
echo $e->getMessage();
return $updated;
}
}
I haven't checked all of your source code, but it is absolutely possible to use AJAX to send some data to the server without the need of <form> tag. Using a form makes it only a lot easier to receive all "form values" at once.
I am posting from a form that selects products from a list, to a page with the selected products displayed. I want to have a link next to each item for removing an item from the selected list (array).
How do I do that? I seem to be losing the session once I click on the remove link.
session_start();
foreach($_SESSION['id'] as $key => $value){
$array = explode(',', $value);
if($value[0]!=''){
$id = $array[0];
$query = "SELECT * FROM products WHERE id = '$id'";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
$product_id = $row['id'];
echo '<tr valign="bottom">';
echo '<td>' . stripslashes($row['category']) . '</a></td>';
echo '<td>' . stripslashes($row['itemDesc']) . '</a></td>';
echo '<td class="right">' . stripslashes(number_format($row['points'], 2)) . '</a></td>';
echo '<td>Remove</td>';
echo "</tr>\n\n";
$points = stripslashes($row['points']);
#$points_total += $points;
}
}
}
$postid = $_POST['id'];
$_SESSION['id'] = $_POST['id'];
$product_id = htmlspecialchars(#$_GET['id'], ENT_QUOTES, 'UTF-8');//the product id from the URL
$s = $_SESSION['id'];
$s = htmlspecialchars(#$_GET['key'], ENT_QUOTES, 'UTF-8');//the product id from the URL
$action = htmlspecialchars(#$_GET['action'], ENT_QUOTES, 'UTF-8'); //the action from the URL
switch($action) {
case "remove":
unset($array[$id]); //remove $product_id from the array with
echo $action . $product_id;
break;
}
Here's the HTML for the form:
<form method="post" action="products_selected.php">
<?php
$query = "SELECT * FROM products ORDER BY rangeCode, category ASC";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
echo '<tr valign="bottom">';
echo '<td>' . stripslashes($row['rangeCode']) . '</td>';
echo '<td>' . stripslashes($row['category']) . '</a></td>';
echo '<td>' . stripslashes($row['itemDesc']) . '</a></td>';
echo '<td>' . number_format($row['points'], 2) . ' points ';
echo '<input type="checkbox" name="id[]" value="' . $id . '" /></td>';
echo '</tr>' . "\n\n";
}
mysqli_close($dbc);
?>
<tr><td colspan=13><input type="submit" name="submit" value="Order" /></td></tr>
Ok. After a bit of chat and co-working around this issue, we found some problems.
There's the need to insert a check around the code that uses $_GET and $_POST data, to avoid unwanted modification to other variables (an example: when the user clicks "Remove" to remove an item from his choices, the $_SESSION array will be updated with the $_POST array; since this contains nothing, the session array is emptied (and this was why the session was thought to be lost):
To find and delete the item from the session, we have to use the key retrieved from url and check if it's present into the session array. This can be seen in the code below.
if (isset($_POST['id']))
{
$_SESSION['id'] = $_POST['id'];
}
if(isset($_GET['key']) && ($_GET['action'] == 'remove'))
{
if (array_key_exists($_GET['key'], $_SESSION['id']))
{
unset($_SESSION['id'][$_GET['key']]);
}
}
Some other minor changes have been made to the code, but the main problems were the ones explained.
<?php
$sample = 0;
if($sample ==0)
{
$displayinner = '<option value =' . $row['privilege_ID'] . '>' . $row['privilege_name'] . '</option>';
$displayouter = '<td><label>Privileges:</label></td>
<td><select name = "Privilege" id = "Privilege" multiple="multiple">
<?php
$PrivilegeNames = mysql_query("SELECT * FROM privilege");
while($row = mysql_fetch_array($PrivilegeNames))
echo $displayinner;
?>
</select></td>
</tr>
<tr>';
echo $displayouter;
}
?>
I only get a dropdownbox without any data inside it. Please help, what am i doing wrong?
Yeah that won't work - there's a lot of issues, your "template" code will be parsed which will cause errors, and you can't nest <?php blocks like that. To get what you want, try this for starters:
$displayouter = '<td><label>Privileges:</label></td><td><select name = "Privilege" id = "Privilege" multiple="multiple">';
$PrivilegeNames = mysql_query("SELECT * FROM privilege");
while($row = mysql_fetch_array($PrivilegeNames)) {
$displayouter .= '<option value =' . $row['privilege_ID'] . '>' . $row['privilege_name'] . '</option>';
}
$displayouter .= '</select></td></tr><tr>';
echo $displayouter;
If you don't need the variable $displayouter later, you can just echo everything instead, or break out of the PHP block entirely if this is template code. Note the use of .=, which appends data to the existing variable.
There's a lot of possible security holes here, but hopefully this helps to see some working code. Make sure to use htmlspecialchars on all unknown HTML output, for one thing.
<?php
$sample = 0;
if($sample == 0)
{
$displayPre = '<td><label>Privileges:</label></td>
<td><select name = "Privilege" id = "Privilege" multiple="multiple">';
$displayPost = '</select></td>
</tr>
<tr>';
$PrivilegeNames = mysql_query("SELECT * FROM privilege");
echo $displayPre;
while($row = mysql_fetch_array($PrivilegeNames))
echo '<option value =' . $row['privilege_ID'] . '>' . $row['privilege_name'] . '</option>';
echo $displayPost;
}
?>
The inner php tags were not parsed correctly, try the code above, it implements the form with a pre and post part so you don't need to put a new php block inside the string
Wesley Murch is close, but missing a few things: Quotes around the value, and using htmlentities to prevent XSS injection.
$displayouter = '<td><label>Privileges:</label></td><td><select name = "Privilege" id = "Privilege" multiple="multiple">';
$PrivilegeNames = mysql_query("SELECT * FROM privilege");
while($row = mysql_fetch_array($PrivilegeNames)) {
$displayouter .= '<option value="' . htmlentities($row['privilege_ID']) . '">' . htmlentities($row['privilege_name']) . '</option>';
}
$displayouter .= '</select></td></tr><tr>';
echo $displayouter;
I haven't tested syntax, but you have made a few misplacements.
<?php
$sample = 0;
if($sample ==0)
{
$displayinner = '<option value =' . $row['privilege_ID'] . '>' . $row['privilege_name'] . '</option>';
?>
<td><label>Privileges:</label></td>
<td><select name = "Privilege" id = "Privilege" multiple="multiple">
<?php
$PrivilegeNames = mysql_query("SELECT * FROM privilege");
while($row = mysql_fetch_array($PrivilegeNames))
echo $displayinner;
?>
</select></td>
</tr>
<tr>
<?php
}
?>