php arrange checkbox values in two columns - php

I have a form with checkboxes and I want to arrange the checkboxes in two columns instead of one single long column.
How can i split it to two columns?
Here is my code:
if($proceder == True) {
echo "<form name='formulario' method='POST' action='iconizar.php'>";
$iconosm = 0;
$server_groups = $ts3_VirtualServer->serverGroupList();
$servergroups = array();
# En vez de iterar por todos los grupos intenten
foreach($server_groups as $group) {
if($group->type != 1) { continue; }
if(in_array($group["sortid"], $SID_GROUP)) {
$servergroups[] = array('name' => (string)$group, 'id' => $group->sgid, 'type' => $group->type);
}
}
$_SESSION['grupos'] = $servergroups;
foreach($servergroups as $group) {
$miembros = $ts3_VirtualServer->serverGroupClientList($group["id"]);
$estaengrupo = False;
foreach($miembros as $m) {
if($m["client_unique_identifier"] == $client_uid) {
$estaengrupo = True;
}
}
if($estaengrupo) {
$iconosm = $iconosm + 1;
echo '<li><img src="./iconos/icons/'.$group['id']. '.png" alt="" /> ';
echo '<label><input type=checkbox name=grupos['.$group["id"].'] id="'.$group["id"].'" value="'. $group["id"] .'"class="icono" checked >'.$group["name"].'</label><br>';
} else {
echo '<li><img src="./iconos/icons/'. $group['id'] . '.png" alt="" /> ';
echo '<label><input type=checkbox name=grupos['.$group["id"].'] id="'. $group["id"] .'" value="'. $group["id"] .'" class="icono"> '.$group["name"].'</label><br>';
}
}

I'm assuming your have additional code not posted that close your form and li elements, but in any case you can do this using CSS. Set a width on your form (or it's wrapping element that will accomodate two of your li elements, side by side, then set the float property to 'left' for your li tags... Using inline styles, you might echo html that looks like this:
form tag:
<form style="width: 400px;" name='formulario' method='POST'>
li tags:
<li style="width 50%;float: left;">...
If you need your checkboxes to appear first half down the left column, then second half down the write, that will involve some PHP.

Where is your unodered element then change to

Related

Keep Page Data on Refresh With $_POST

<!DOCTYPE html>
<html lang="en">
<head>
<h1>Table Generator</h1>
</head>
<body>
<center>Refresh</center>
<?php
$rows = (isset($_POST['rows']) ? $_POST['rows'] : null);
$cols = (isset($_POST['cols']) ? $_POST['cols'] : null);
$highlight = (isset($_POST['highlight']) ? $_POST['highlight'] : null);
if ($rows == "")
{
$rows = 10;
}
if ($cols == "")
{
$cols = 10;
}
if ($highlight == "")
{
$highlight = 5;
}
?>
<form method="post">
ROWS <input type="text" name="rows" value = "<?php echo $rows;?>" />
COLUMNS <input type="text" name="cols" value = "<?php echo $cols;?>" />
HIGHLIGHT <input type = "text" name = "highlight" value = "<?php echo $highlight;?>" /><br>
<input type="submit" value="Generate">
</form>
<?php
if(isset($_POST['rows']))
{
$randnumber = rand(0,100);
$rows = $_POST['rows'];
$cols = $_POST['cols'];
$highlight = $_POST['highlight'];
echo '<table border="1" align = "center">';
if (is_numeric($rows) and is_numeric($cols) and is_numeric($highlight))
{
if ($randnumber % 2 == 0)
{
echo '<center>The first number is <div class = "red">even</div></center>';
}
else
{
echo '<center>The first number is <div class = "green">odd</div></center>';
}
for($row = 1; $row <= $rows; $row++)
{
echo '<tr style = "background-color:green">';
for($col = 1; $col <= $cols; $col++)
{
if ($randnumber % $highlight == 0)
{
echo '<td style = "background-color: red">';
echo $randnumber;
$randnumber++;
echo '</td>';
}
else
{
echo '<td>';
echo $randnumber;
$randnumber++;
echo '</td>';
}
}
echo '</tr>';
}
echo '</table>';
}
else
{
echo "<center>Rows / Columns / Highlight must ALL be INTEGER values. Re-enter correct value(s).</center>";
}
echo '<pre><center>';
print_r($_POST);
echo '</center></pre>';
}
?>
<style type ="text/css">
h1 {
color: grey;
text-align:center;
}
form {
text-align: center;
padding-bottom: 20px;
}
a:link {
text-decoration: none;
}
.red {
color: red;
}
.green {
color: green;
}
</style>
</body>
</html>
So. I have this PHP code to generate a table based off the user's input and I recently ran into a problem I cant figure out how to fix.
It was working perfectly fine but now whenever I use the Refresh link it resets the entire page to default (i.e. default textbox values instead of keeping the current ones, removing the table).
So, I have 2 questions. How would I keep the data on refresh (with $_POST being used) and how to display the table with the default values when the page first loads.
Refresh
Clicking it will trigger browser's reload mechanism and you'll be asked to resubmit the form action, it will allow you to keep POST data.
You need to re-create the post if you want to keep the parameters. Can be done pretty eaily by looping thru the array.
<form method='POST' id='refresh' action='<?php echo $_SERVER['PHP_SELF']; ?>'>
<?php foreach($_POST as $k=>$v): ?>
<input type='hidden' name='<?php echo $k; ?>' value='<?php echo $v; ?>' />
<?php endforeach; ?>
<a href='#' onclick='document.getElementById("refresh").submit(); return false;'>refresh</a>
</form>
Note: This is a little longer than the other answer, but will not prompt to resend post data.

PHP, mulitchoice FORMS, how to pass variable selected in form,

and show form based on that variable in single page, without pressing SUBMIT or buttons?
i have loop for fill 'select' in FORM
echo '<select name="inne_zad" class="cfpa" width="400" style="width: 400px" >';
echo '<option value="">Nr Zadania | Typ Zadania | Nazwa Wioski</option>';
while($option = mysql_fetch_assoc($zadanie1)) {
echo '<option value="'.$option['id_zadania'].'">'.' '.$option['id_zadania'].' - '.$option['rodzaj_zadania'].' - '.$option['zad_cel_nazwa'].' '.'</option>';
}
echo '</select>';
and css rule
<style>
.cfp { display: none; }
.cfpa:checked + .cfp {
display: block;
}
</style>
and div outside form (inside FORM css display none - not working..
echo ' <div class="cfp">';
echo ' some other content';
if ($_POST['id_zadania'] == 7 ){ echo 'wybrales 7'; }
echo ' </div>';
I want to get selected variable, and display other part of the FORM
is it possible with PHP and CSS only?
If you don't want to press a button you can use the event onChange.
echo '<form>
<select name="inne_zad" class="cfpa" width="400" style="width: 400px" onChange="this.form.submit();" >';

Unique Value For Each Button

I have two php pages. The first page queries a database and places some data into a form
The second page, grabs the data submited from the previous page and displays the data.
THE ISSUE:
On the second page, the information is displayed in a table. At the end of each row, there is a "information" button that allows the user to click and see more details related to the data in that particular column. For some reason, the information button for every record in the table is holding the value of the first record returned in the database query. In other words no matter what button I click on in the table, it always relates to the first record returned in the query.
I'm hoping someone can help me find a solution to linking each "information" button to each unique record. In other words If I click the info button in row one, it will display the data for the record related to row 1...etc. Here's my code.
PAGE 1
<?php
$query = mysql_query ("SELECT * from cust_data group by cabinet_number ORDER by cabinet_number ASC");
WHILE ($rows = #mysql_fetch_array($query)) {
if (($rows['account_number']=="") &&
($rows['customer_first_name']=="") &&
($rows['customer_last_name']=="") &&
($rows['company_name']=="")) {
echo '<form method="GET" action="cabinet_result_page.php">
<input type="hidden" value="'.$rows['cabinet_number'].'" name="cabinet_number">
<input type="hidden" value="'.$rows['company_name'].'" name="company_name">
<img src="images/bulletpoint_green.png">
<input type="submit" value="'.$rows['cabinet_number'].'" name="'.$rows['cabinet_number'].'" id="submit">
</form>';
} else if ($rows['cabinet_number']!=="") {
echo '<form method="GET" action="cabinet_result_page.php">
<input type="hidden" value="'.$rows['cabinet_number'].'" name="cabinet_number">
<input type="hidden" value="'.$rows['company_name'].'" name="company_name">
<img src="images/bulletpoint_red.png">
<input type="submit" value="'.$rows['cabinet_number'].'" name="'.$rows['company_name'].'" id="submit">
</form>';
}
}
}
PAGE 2:
GRABS THE DATA IN PAGE ONE AND PLACES IT IN A TABLE. WHEN THE 'INFO' BUTTON IS CLICKED, MORE INFORMATION IS DISPLAYED IN A JQUERY POPUP
db_connect();
$cabinet_number = $_GET['cabinet_number'];
$company_name = $_GET['company_name'];
$query = #mysql_query ("SELECT * FROM cust_data WHERE cabinet_number = '$cabinet_number' ");
WHILE ($rows = #mysql_fetch_array($query)) {
echo'<tr>
<td><font size="4">'; echo $rows['account_number']; echo'</font></td>
<td><font size="4">'; echo $rows['customer_first_name']; echo '</font></td>
<td><font size="4">'; echo $rows['customer_last_name']; echo '</font></td>
<td><font size="4">'; echo $rows['company_name']; echo '</font></td>
<td><font size="4">'; echo $rows['cabinet_number']; echo'</font></td>
<td><font size="4">'; echo $rows['key_tag_number']; echo'</font></td>';
if ($rows['switch_and_port1'] =="") {
echo '';
} else if ($rows['switch_and_port1'] !== "") {
echo '<td><font size="4">';
echo '<input type = "image" src= "images/view_details.png" height="16" width="16" class="my_modal_open">', '</font></td>';
}
{
echo '<td><font size="4">'; echo '<input type = "image" src= "images/view_details.png" height="16" width="16" class="my_modal_open">', '</font></td>';
}
echo '</tr>';
echo '<div class="well" style="display:none;margin:1em;" class="my_modal">';
echo '<img src="images/hdc_logo_transparent.png"><br>';
echo '<div style="height:23px; width:100%; background-color:black"> <h4><font color="#FFFFFF">',' ', 'Cabinet: ', $id, '</font></h4></div>';
echo '<p>';
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Power: ', $rows['power_circuit'];
echo '<br>';
echo'<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port1'];
if ($rows['switch_and_port2'] =="") {
echo '';
} else if ($rows['switch_and_port2'] !== "") {
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port2'];
}
if ($rows['switch_and_port3'] =="") {
echo '';
} else if ($rows['switch_and_port3'] !== "") {
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port3'];
}
if ($rows['switch_and_port4'] =="") {
echo '';
} else if ($rows['switch_and_port4'] !== "") {
echo '<br>';
echo '<img src="images/bulletpoint_orange.png">';
echo 'Sw/Po: ', $rows['switch_and_port4'];
}
echo '</p>';
echo'</div></form>';
}
echo'<script>
$(document).ready(function() {
$(".my_modal_open").click(function(){
$(this).closest("tr").next(".my_modal").popup({"autoopen": true});
});
});
});
</script>
</body>
</html>';
}
The issue is that you are setting the same id attribute to all the modals (which is invalid HTML markup) and expecting the click handler on the button to figure out which one to open.
UPADTE
Another issue with your markup is that you can't have <div>s as siblings of a table row, it will produce unexpected results as browsers will attempt to fix the markup and rearrange the elements, you could place the divs inside a td or use a second loop to build them.
Now I also did some digging in your popup plugin and I must say it's not very well implemented, I would recommend you look for another one. That being said I did manage to get it working, here's what you need to do:
Set an unique id for each of the modal divs, if you have some sort of id in your database data you can use that, if not then you can set up a counter variable inside the loop:
echo '<div class="well" id="my_modal'.$rows['id'].'">';
Use the same id as the class for the button that should open the modal but add "_open" as a suffix:
echo '<input type = "image" src="images/view_details.png" height="16" width="16" class="my_modal'.rows['id'].'_open">
You can now initialize the popup plugin on your divs and it will automatically assign the open action to the corresponding button:
echo'<script>
$(document).ready(function () {
$("[id^=\'my_modal\']").each(function () {
$(this).popup();
});
});
</script>';
That should fix the modal problem, here's a working demo.
Now I also have a couple observations about your code:
You should avoid the use of inline styles and as I mentioned earlier the <font> tag should be replaced for proper CSS, I would also suggest using CSS padding/margin to add space between words instead of
This type of code:
if ($rows['switch_and_port1'] =="") {
echo '';
} else if ($rows['switch_and_port1'] !== "") {
echo 'SOME CONTENT';
}
can be optimized to just:
if ($rows['switch_and_port1'] !== "") {
echo 'SOME CONTENT';
}
echoing an empty string produces no output whatsoever and there's no need for an elseif

Adding mouseover effect to dynamic checkbox

I would like to ask for help on how to implement mouseover to checkbox. What I wan't to achieve is that I want to have mouseover when someone point the cursor to the checkbox based on subject description.
Below is my code to generate dynaminc checkbox but I don;t know how to add mouseover to it. thanks.
<?php
$subjects = $stmt->prepare("SELECT * FROM subjects");
$stmt->execute();
$cols = 5;
do
{
echo "<tr>";
for ($i = 1; $i <= $cols; $i++)
{
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row)
{
$sub_id = $row['sub_id'];
$sub_name = $row['sub_name'];
$sub_desc = $row['sub_desc']
?>
<table>
<tr><td>
<?php
echo '<input type="checkbox" sub_id="sub_id[]" name="sub_id[]" value="' . $id_tag . "\"" .'/>' . $tag_name . "\n";
?>
</td></tr>
</table>
<?php
} else {
echo "<td> </td>";
}
}
} while ($row);
?>
When you generate the HTML, you add a CSS class. And then, in your stylesheet, you define a hover effect. Like this:
echo '<input type="checkbox" class="HoverOnCheckbox" sub_id="sub_id[]" name="sub_id[]" value="'
.HoverOnCheckbox{
color:green;}
.HoverOnCheckbox:hover{
color:red;}
<script type="text/javascript">
function myfn() {
var myInput = event.target;
myInput.style.fontSize = "1.2em";
//some else...
}
</script>
<?php
echo '<input type="checkbox" onmouseover="myfn();" title="'.$row['sub_desc'].'" sub_id="sub_id[]" name="sub_id[]" value="' . $id_tag . "\"" .'/>' . $tag_name . "\n";
?>
There's many way to attach events in JavaScript. Another implement is using CSS.
<style type="text/css">
input:hover { font-size:1.2em; }
</style>
$(function() {
$('input[type="checkbox"]').each(function() {
$(this).hover(function(){
//mouseover effect
},function(){
//mouseout effect
});
});
});
EDIT: as #Repox suggested this will work with jquery

How to keep already-set GET parameter values on form submission?

I have a URL : foo.php?name=adam&lName=scott, and in foo.php I have a form which gives me values of rectangleLength & rectangleBreadth with a submit button.
When I click this submit button with form action as $_SERVER['REQUEST_URI'], I get this result URL: foo.php?rectangleLength=10&rectangleBreadth=5 (these values have been filled in by the user).
Notice that I am losing my previous values name & lName from the URL.
How can I keep them?
Also, keep in mind that I have to come back to foo.php and if the user wants to submit the form again then the length and breadth values should change.
You can add two hidden fields in the form on the first target site, blabla.php in your case:
<form ...>
<input type="hidden" name="name" value="<?php echo htmlspecialchars($_GET['name']);?>">
<input type="hidden" name="lName" value="<?php echo htmlspecialchars($_GET['lName']);?>">
<!-- rest of the form here -->
</form>
For a dynamic solution, use a foreach loop:
<?php
foreach($_GET as $name => $value) {
$name = htmlspecialchars($name);
$value = htmlspecialchars($value);
echo '<input type="hidden" name="'. $name .'" value="'. $value .'">';
}
?>
You may consider locking the dynamic approach down to a list of known possible keys:
<?php
$keys = array('name', 'lName', ...);
foreach($keys as $name) {
if(!isset($_GET[$name])) {
continue;
}
$value = htmlspecialchars($_GET[$name]);
$name = htmlspecialchars($name);
echo '<input type="hidden" name="'. $name .'" value="'. $value .'">';
}
?>
A simpler solution to keep the URL unchanged by using http_build_query
<form action="<?php echo $_SERVER["PHP_SELF"] . '?'.http_build_query($_GET); ?>" ...
..
..
There are different ways to do this. All of them write the parameters they receive into a file, memory, or a database and retrieve them later with a key
The easiest method is something like a session variable: http://php.net/manual/en/features.sessions.php
The main setup is something like this (caution: that is unsecure code, make sure you only add session variables you want to keep, and sanitize user input!):
<?php
session_start();
foreach ($_GET as $key=>$value) {
$_SESSION[$key]=>$value;
}
?>
and now, as long as the user does not close the browser, you can access these variables with $_SESSION[varname];
Once, I needed sorting the results in a table keeping the search results coming from GET. I did like that:
unset($_GET['sort']); // sort param is removed, otherwise there will be created many sort params
$url = http_build_query($_GET);
echo "<a href='?".$url."&sort=title'>Title</a>";
echo "<a href='?".$url."&sort=author'>Author</a>";
To handle query with arrays:
foreach (explode("\n", http_build_query($query, '', "\n")) as $keyValue) {
[$key, $value] = explode('=', $keyValue, 2);
$key = htmlspecialchars(urldecode($key), ENT_COMPAT | ENT_HTML5);
$value = htmlspecialchars(urldecode($value), ENT_COMPAT | ENT_HTML5);
echo '<input type="hidden" name="' . $key . '" value="' . $value . '"' . "/>\n";
}
Following code works for my project. Hope it help some.
1. In menu (calling html) I call VendorSearch.php. variable fromvs is used in URL.
2. The target php VendorSearch.php will do different jobs based on the value of $_GET['fromvs']
3. In VendorSearch.php, aftersession_start(),
$srchfor ="";
$fromwhat = $_GET['fromvs'];
$_SESSION['fromwhat'] = $fromwhat;
//save value to $VS
$vs = $fromwhat;
3. Use hidden input to store URL passed variable
<div style='position: absolute; top: 10px; left: 400px;'><input type='hidden' hidden='hidden' id='fromvs' name='fromvs' value="<?php echo $_SESSION['fromwhat']; ?>"></div>
4. But this thie field's value may lost after clicking button "srchvnd". So use a function to reset
$_SESSION['fromwhat'];
if (isset($_POST['srchvnd']))
{
$vs = $_POST['fromvs'];
somefunction($vs);
}
-----------------Source code----------------------
Segment in Calling html
....
<body>
<div style=" position: absolute; top: 1px; left: 5px; height:740px; width:205px; border-radius: 10px;" >
<!-- Start css3menu.com BODY section -->
<ul id="css3menu1" class="topmenu">
<li class="topfirst">Add a Subcontractor </li>
....
<li class="topmenu">Assign Subcontractor Contracts</li>
.....
<li class="toplast">Log Out</li>
</ul>
....
</div>
Segment in target php: VendorSearch.php
<?php
//VendorSearch.php
//http://mted202.mtaent.org:9051/ocr/login.php rweinbau
require_once('dbinfo.php');
session_start();
$c = oci_pconnect("ocr","ocrmta","HQT4");
oci_set_client_identifier($c, $_SESSION['username']);
$username = htmlentities($_SESSION['username'], ENT_QUOTES);
.....
$srchfor ="";
$fromwhat = $_GET['fromvs'];
$_SESSION['fromwhat'] = $fromwhat;
$vs = $fromwhat;
if (isset($_POST['srchvnd']))
{
$vs = $_POST['fromvs'];
somefunction($vs);
}
else
{
;
}
?>
<body>
<form class="vfrmsrch" name="vndsearch" id="vndsearch" action="VendorSearch.php?fromvs='<?php echo $fromwhat; ?>'" method="POST">
<div style='position: absolute; top: 10px; left: 400px;'><input type='hidden' hidden='hidden' id='fromvs' name='fromvs' value="<?php echo $_SESSION['fromwhat']; ?>"></div>
......
<td><input type="submit" class="slbt" name="srchvnd" id ="srchvnd" vaue="Search"></input></td>
......
</form>
.......
</body>
</html>
<?php
function somefunction($vvs){
//$msg = "We are inf somefunction() function </a></div><br>";
// echo "<div style='position: absolute; top: 100px; left: 10px;'><a style='color:blue'>".$msg;
$_SESSION['fromwhat'] = $vvs;
............
oci_close($c);
}
In menu (calling html) I call VendorSearch.php. variable fromvs is used in URL.
The target php VendorSearch.php will do different jobs based on the value of $_GET['fromvs']
In VendorSearch.php, aftersession_start(),
$srchfor ="";
$fromwhat = $_GET['fromvs'];
$_SESSION['fromwhat'] = $fromwhat;
$vs = $fromwhat;
Use hidden input to store URL passed variable
<div style='position: absolute; top: 10px; left: 400px;'><input type='hidden' hidden='hidden' id='fromvs' name='fromvs' value="<?php echo $_SESSION['fromwhat']; ?>"></div>
But this thie
Segment in Calling html
....
Add a Subcontractor
....
Assign Subcontractor Contracts
.....
Log Out
....
Segment in target php: VendorSearch.php
<?php
//VendorSearch.php
//http://mted202.mtaent.org:9051/ocr/login.php rweinbau
require_once('dbinfo.php');
session_start();
$c = oci_pconnect("ocr","ocrmta","HQT4");
oci_set_client_identifier($c, $_SESSION['username']);
$username = htmlentities($_SESSION['username'], ENT_QUOTES);
.....
$srchfor ="";
$fromwhat = $_GET['fromvs'];
$_SESSION['fromwhat'] = $fromwhat;
$vs = $fromwhat;
if (isset($_POST['srchvnd']))
{
$vs = $_POST['fromvs'];
somefunction($vs);
}
else
{
;
}
?>
<body>
<form class="vfrmsrch" name="vndsearch" id="vndsearch" action="VendorSearch.php?fromvs='<?php echo $fromwhat; ?>'" method="POST">
<div style='position: absolute; top: 10px; left: 400px;'><input type='hidden' hidden='hidden' id='fromvs' name='fromvs' value="<?php echo $_SESSION['fromwhat']; ?>"></div>
......
</form>
.......
</body>
</html>
<?php
function somefunction($vvs){
//$msg = "We are inf somefunction() function </a></div><br>";
// echo "<div style='position: absolute; top: 100px; left: 10px;'><a style='color:blue'>".$msg;
$_SESSION['fromwhat'] = $vvs;
............
oci_close($c);
}
My personal preference would be to specify the keys you wish to accept and be sure to run the value through htmlspecialchars().
$url_params = array(
'tab'
);
foreach( $url_params as $key ) {
echo !empty( $_GET[$key] ) ? '<input type="hidden" name="'. $key .'" value="'. htmlspecialchars( $_GET[$key] ) .'" />' : '';
}

Categories