I'm trying to check checkboxes based on previous user preferences that are stored in a CSV, but it is only running checking the first index in the CSV and skipping the rest. In the following code below if I pass it a CSV of "Sports, Lowkey, Wine" I want it to check those three on page load but it is only checking Sports
$typeArray = array(
"1" => "Sports",
"2" => "College",
"3" => "Pub",
"4" => "Night Club",
"5" => "Lowkey",
"6" => "Wine",
"7" => "Craft Beer",
);
$Sports="";
$College="";
$Pub="";
$NightClub="";
$Lowkey="";
$Wine="";
$CraftBeer="";
$string = "Sports, Lowkey, Wine";
$csv = str_getcsv($string, ", ");
for($i=0; $i<count($csv); $i++){
$index = array_search($csv[$i], $typeArray);
if($index == 1){
$Sports = "checked";
}
if($index == 2){
$College = "checked";
}
if($index == 3){
$Pub = "checked";
}
if($index == 4){
$NightClub = "checked";
}
if($index == 5){
$Lowkey = "checked";
}
if($index == 6){
$Wine = "checked";
}
if($index == 7){
$CraftBeer = "checked";
}
unset($index);
}
echo "<input type=\"checkbox\" name=\"Type[1]\" value=\"Sports\"" . $Sports . ">Sports ";
echo "<input type=\"checkbox\" name=\"Type[2]\" value=\"College\"" . $College . ">College ";
echo "<input type=\"checkbox\" name=\"Type[3]\" value=\"Pub\"" . $Pub . ">Pub ";
echo "<input type=\"checkbox\" name=\"Type[4]\" value=\"Night Club\"" . $NightClub . ">Night Club ";
echo "<input type=\"checkbox\" name=\"Type[5]\" value=\"Lowkey\"" . $Lowkey . ">Lowkey<br> ";
echo "<input type=\"checkbox\" name=\"Type[6]\" value=\"Wine\"" . $Wine . ">Wine ";
echo "<input type=\"checkbox\" name=\"Type[7]\" value=\"Craft Beer\"" . $CraftBeer . ">Craft Beer<br> ";
exchange this line
$index = array_search($csv[$i], $typeArray);
with this:
$index = array_search(trim($csv[$i]), $typeArray);
When you do a var_dump of $csv you will notice that there is a space before Lowkey and Wine:
array(3) {
[0]=> string(6) "Sports"
[1]=> string(7) " Lowkey"
[2]=> string(5) " Wine"
}
So your array_search will fail.
According to the manual, the delimiter in str_get_csv can be only one character. You can use explode or trim instead.
$csv = explode(', ', $string);
// or
$index = array_search(trim($csv[$i]), $typeArray);
Related
I'm trying to add checkboxes to each cell in my table.
If $columns['mything$record'] is equal to 1, I want a checkbox that's checked to show up.
If $columns['mything$record'] is equal to 0, I want a blank checkbox to show up. I've created if statements which one can view below, but they don't put a checkbox in each table cell with the respective value, only one blank checkbox appears at the top of the page.
How can I put checkboxes in each cell that are checked and unchecked based on the cell value?
[![screenshot][1]][1]
$stmt = $sql->prepare("SELECT record,shortName FROM dms
where dms.isInactive=0
ORDER BY lastName asc, firstName asc");
$stmt->execute();
$shortNameArray=array();
while ($row = $stmt->fetch()) {
// print_r($row);
$shortNameArray[$row['record']]=$row['shortName'];
}
//print_r($shortNameArray);
$columns = array(
1 => array(
"selectFieldName" => "nrs.record nrRecord",
"resultFieldName" => "nrRecord",
"headerName" => "NT#",
"defaultSortOrder" => -1,
),
array(
"selectFieldName" => "nrs.title",
"resultFieldName" => "title",
"headerName" => "Title",
"defaultSortOrder" => 1,
),
);
$selectedColumnNumbers = array(1,2,3);
$counter=4;
foreach($shortNameArray as $record=>$name){
if($record>0){
$columns[]=array(
"selectFieldName" => "CASE WHEN $record IN (GROUP_CONCAT(dm_nr_links.dmRecord)) THEN 1 ELSE 0 END mything$record",
"resultFieldName" => "mything$record",
"headerName" => "$name",
"defaultSortOrder" => 1,
);
$selectedColumnNumbers[]=$counter;
$counter++;
if ($columns['mything$record'] == 1) {
echo "<input type='checkbox' name='PLJan' checked='checked' />";
}
if ($columns['mything$record'] == 0) {
echo "<input type='checkbox' name='JLFeb' />";
}
}
}
$selectedColumns = array();
$selectedFields = array(); // contains all the fields to be selected
foreach ($selectedColumnNumbers as $columnNumber){
$selectedColumns[$columnNumber] = $columns[$columnNumber];
if (strlen($columns[$columnNumber]["selectFieldName"]) > 0)
$selectedFields[] = $columns[$columnNumber]["selectFieldName"];
}
$selectedFields = array_unique($selectedFields); // Remove all duplicate fields for selection
///// Process Filter Cookies
$filterWhereString = "";
$filterBindValues = array();
for ($c=1; $c<=5; $c++) {
if (isset($_COOKIE["nrsfl$c"])
&& isset($_COOKIE["nrsfl$c"."Op"])
&& isset($_COOKIE["nrsfl$c"."Val"])
&& strlen($_COOKIE["nrsfl$c"."Val"]) > 0
) {
$columnNumber = $_COOKIE["nrsfl$c"];
$filterOperator = $_COOKIE["nrsfl$c"."Op"];
$filterValue = $_COOKIE["nrsfl$c"."Val"];
if (isset($columns[$columnNumber])){
if ($c >= 2) {
$lastC = ($c-1);
if (strlen($filterWhereString) > 0) // If string exists, add conjunction
{
if (isset($_COOKIE["nrsfl$lastC"."C"])){
$conSelect = $_COOKIE["nrsfl$lastC"."C"];
} else $conSelect = 1;
if ($conSelect == 1) $conjunction = "AND";
else $conjunction = "OR";
$filterWhereString .= "$conjunction ";
}
}
$column = $columns[$columnNumber];
$fieldName = $column['resultFieldName'];
$filterWhereString .= "$fieldName ";
switch ($filterOperator) {
case 1:
$operator = "=";
break;
case 2:
$operator = "LIKE";
break;
case 3:
$operator = ">=";
break;
case 4:
$operator = "<=";
break;
case 5:
$operator = ">";
break;
case 6:
$operator = "<";
break;
case 8:
$operator = "NOT LIKE";
break;
default:
$operator = "!=";
}
if ((strcmp($operator, "NOT LIKE") == 0) ||(strcmp($operator, "LIKE") == 0)) $filterField = "CONCAT('%',:filter".$c.",'%')";
else $filterField = ":filter$c";
$filterWhereString .= "$operator $filterField ";
if (substr_compare($fieldName, "date", 0, 4) == 0) { // Convert dates
$filterValue = strtotime($filterValue);
$filterValue = date("Y-m-d",$filterValue);
}
if ($fieldName=="isRestricted") { // Convert binaries
if(strtolower($filterValue)=='y')$filterValue="1";
if(strtolower($filterValue)=='n')$filterValue="0";
}
$filterBindValues[":filter$c"] = $filterValue;
}
}
}
/////
?>
Replace your code line
echo "<input type='checkbox' name='PLJan' ";
echo "checked='checked'";
with
echo "<input type='checkbox' name='PLJan' checked='checked' />";
and
echo "<input type='checkbox' name='JLFeb' ";
with
echo "<input type='checkbox' name='JLFeb' />";
Hy,
how I retrieve information from an associative array like list in php.
var_dump shows something like this:
array(2) { [1]=> string(1) "1"
[2]=> string(1) "2" }
array(2) { [1]=> string(15) "gica_craioveanu"
[2]=> string(14) "alexandra_minu" }
array(2) { [0]=> string(10) "craiovaMAX"
[1]=> string(10) "alexMinu10" }
First array containd the id's, second the user name and third the passwords.
My attempt:
foreach ($row as $i => $id,$user_name,$user_pass) {
echo "<tr>\n" .
" <td>".var_dump($id)."</td>\n".
" <td>".var_dump($user_name)."</td>\n".
" <td>".var_dump($user_pass)."</td>\n".
" </tr>\n"
}
one of php file contains the script to construct the list:
while($row = mysqli_fetch_row($result))
{
/*$id[]=$row['user_id'];
$user_name[]=$row['user_name'];
$user_pass[]=$row['user_pass'];
$i=$i+1;*/
list($id[$i],$user_name[$i],$user_pass[$i++])=$row;
}
/*for($no=0; $no<$i; $no++){
echo $row[$i]."/".$row[$i]."/";
}*/
include 'user.html.php';
}
?>
and the user.html.php
to view the rows:
<?php
// while (list($id, $user_name, $user_pass)= each($row)) {
foreach($row as $i => $id,$user_name,$user_pass){
echo " <tr>\n" .
" <td>".$id."</td>\n".
" <td>".$user_name."</td>\n".
" <td>".$user_pass."</td>\n".
" </tr>\n";
/*echo "<tr>\n" .
" <td>".var_dump($id)."</td>\n".
" <td>".var_dump($user_name)."</td>\n".
" <td>".var_dump($user_pass)."</td>\n".
" </tr>\n"
*/
/*for($no=0; $no<$i; $no++){
echo "<tr>".
"<td>".$row[$i]."</td>".
"<td>".$row[$i]."</td>".
"<td>".$row[$i]."</td>".
"</tr>";*/
}
?>
while($row = mysqli_fetch_row($result)) {
list($id[$i],$user_name[$i],$user_pass[$i++])=$row;
}
...
for($i = 1; $i < count($id) + 1; $i++) {
echo " <tr>\n" .
" <td>".$id[$i]."</td>\n".
" <td>".$user_name[$i]."</td>\n".
" <td>".$user_pass[($i - 1)]."</td>\n".
" </tr>\n";
}
$id = array("1", "2");
$user_name = array("gica_craioveanu", "alexandra_minu");
$user_pass = array("craiovaMAX", "alexMinu10");
We presume that 3 arrays are always the same size :
// You make a loop on first array
for ( $i = 0 ; $i < count($id) ; $i++ )
{
// You use index $i to access to 3 arrays.
echo 'ID: '.$id[$i].'<br />';
echo 'Name: '.$user_name[$i].'<br />';
echo 'Password: '.$user_pass[$i].'<br />';
}
for($no=1; $no<$i+1; $no++)
{
echo "<tr>".
"<td>".$id[$no]."</td>".
"<td>".$user_name[$no]."</td>".
"<td>".$user_pass[($no-1)]."</td>".
"</tr>";
}
Inspired by Typoheads
I'm totally new at this and have run into a small glitch on a new install and I'm not sure how to fix it.. :(
The error is apparently on this line of code:
$r2->$k = htmlspecialchars($r2->$k);
Here is the code above and below:
// Display items
while ($r2 = mysql_fetch_object($qr2)) {
reset($_bnr_list);
echo "<tr>\n";
$i = 0;
while (list($k, $v) = each($_bnr_list)) {
$i++;
$r2->$k = htmlspecialchars($r2->$k);
if ($kq)
$r2->$k = preg_replace($ks, "<b>\\0</b>", $r2->$k);
echo "<td class=row2>";
if ($i == 1)
echo "Edit: <a href=admin.php?a=bnr/edit&id={$r2->id}&{$_fwk_id}>", ($r2->$k != "" ? $r2->$k : "no name"), "</a>";
elseif ($i == 2) {
$mod = "usr";
list($un) = mysql_fetch_row(mysql_query("SELECT username FROM " . $GLOBALS["_{$mod}_tables"]['list'][0] . " WHERE id={$r2->$k}"));
echo "<a href=admin.php?a={$mod}/info&id={$r2->$k}&{$_fwk_id}>{$un}</a>";
} elseif ($i == 5)
echo round($r2->stat_clicks * 100 / $r2->stat_shows, 3), "%";
else
echo ($r2->$k != "" ? $r2->$k : " ");
echo "\n";
}
echo "<td class=row2><small>",
"<!--- <a href=admin.php?a=bnr/del&id={$r2->id}&{$_fwk_id} {$_fwk_js_confirm}>Delete</a> --->",
"</small>";
echo "<tr><td colspan=", ($col + 1), ">", $r2->html;
}
That error means $k is empty and can not be used as property name. $k is the key from $_bnr_list so you have to trace where does it come from and why does it have empty strings / null values as keys.
If the value is 1 the cell bg is green with the # 1 in the cell
If the value is 0 the cell bg is yellow with a 0 in it.
I would like to display "Yes" instead of "1" and "No" instead of "0"
if($row['play'] == 1){
echo "<td bgcolor='green'>" . $row['play'] . "</td>";
}
else if ($row['play'] == 0){
echo "<td bgcolor='yellow'>" . $row['play'] . "</td>";
}
The values come from a checkbox (1) and a hidden field (0) The MySQL field is BOOL.
Is there an easier/better way to achieve this?
You can do this:
if($row['play'] == 1){
echo "<td bgcolor='green'>Yes</td>";
}
else if ($row['play'] == 0){
echo "<td bgcolor='yellow'>No</td>";
}
but I'd say that switch/case thing is more comfortable:
switch( $row['play'] ) {
case 1:
echo "<td bgcolor='green'>Yes</td>";
break;
default:
echo "<td bgcolor='yellow'>No</td>";
break;
}
You can cast it to an int, and then make a condition if it's above zero:
if((int)$row['play'] > 0) {
echo "<td bgcolor='green'>Yes</td>";
}
else {
echo "<td bgcolor='yellow'>No</td>";
}
This way, play could be 1, 2, 3, 4, 5, ..etc.
something like this will do it -
echo "<td bgcolor='" . $row['play'] == 1 ? "green" : "yellow" . "'> . $row['play'] == 1 ? "No" : "Yes" . "</td>";
You can cut down on an echo statement by doing:
if($row['play'] == 1){
$color = 'green';
$text = 'yes';
}
else
{
$color = 'red';
$text = 'no';
}
// Assign the color and text values based on the input.
echo "<td bgcolor=$color>$data</td>";
$words = array(
0 => "No",
1 => "Yes"
) ;
if($row['play'] == 1){
echo "<td bgcolor='green'>" . $words[(int)$row['play']] . "</td>";
} else if ($row['play'] == 0){
echo "<td bgcolor='yellow'>" . $words[(int)$row['play']] . "</td>";
}
Or even better:
$map = array(
0 => array("word"=>"No", "color"=>"yellow"),
0 => array("word"=>"Yes", "color"=>"green"),
) ;
$current = (int) $row['play'] ;
echo "<td bgcolor='{$map[$current]['color']}'>{$map[$current]['word']}</td>";
Try This
if($row['play'] == 1)
{
echo "<td bgcolor='green'>Yes</td>";
}
else if ($row['play'] == 0)
{
echo "<td bgcolor='yellow'>No</td>";
}
I'm baffled about a problem I have with PHP and a 2-dim associative array. I'm in a class for PHP and the instructor is rather clueless.
I declare the array to make it global with some information. I use an html form to display the data from the array. I modify two null values in the array with an html form "calc" button. Everything works great. The array is updated. I then use a form "order" button to create a text file using the array values. This is when it gets weird. The modified values in the array are gone. I can create and save the text file within the $_Post calc If statement just fine. Same text using the $_Post submit button - gives me the old null values.
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>Online Orders</title>
</head>
<body>
<?php
function DisplayTable(){
echo "<h2 style ='text-align:center'>Online Order</h2>\n";
echo "<p>Enter the desired items you wish to order:</p>\n";
echo "<form action='OnlineOrders.php' method ='POST'>";
echo "<table style='background-color:lightgray' border='1' width='80%'>";
echo "<tr><td width = '10%' style = 'text-align:center'><span style = 'font-weight:bold'>Item</span></td>
<td width = '40%' style = 'text-align:center'><span style = 'font-weight:bold'>
Description</span></td>";
echo "<td width = '10%' style = 'text-align:center'><span style = 'font-weight:bold'>Price</span></td>";
echo "<td width = '10%' style = 'text-align:center'><span style = 'font-weight:bold'>Quantity</span></td>";
echo "<td width = '10%' style = 'text-align:center'><span style = 'font-weight:bold'>Total</span></td></tr>";
//foreach($products as $item){
global $products;
for ($i = 0; $i < count($products); ++$i){
$name = key($products);
echo "<tr><td style = 'text-align:left'>" . $name . "</td>";
echo "<td style = 'text-align:left'>" . $products[$name]['Description']. "</td>";
echo "<td style = 'text-align:center'>" . $products[$name]['Price']. "</td>";
if($products[$name]['Quantity'] > 0)
$value = $products[$name]['Quantity'];
else
$value = "";
echo "<td style = 'text-align:left'><input type='text' name = 'quantity[" . $name ."]' value = $value></td>";
if($products[$name]['Total'] > 0)
echo "<td style = 'text-align:left'>" . $products[$name]['Total']. "</td>";
else
echo "<td></td>";
echo "</tr>";
next($products);
}
echo "</table>";
echo "<p></p>";
echo "<input type ='submit' name='submit' value='Order' />";
echo "<input type ='submit' name='calc' value='Calculate' />";
echo "</form>";
}
//creates data array
$pencils = array("Price" => "1.50", "Description" =>"12pk of #2 pencils", "Quantity" => NULL, "Total" => NULL);
$pens = array("Price" => "3.50", "Description" =>"12pk of Bic blue ink pens", "Quantity" => NULL, "Total" => NULL);
$paper = array("Price" => "5.50", "Description" =>"6pk of letter-sized, 100 count paper pads",
"Quantity" => NULL, "Total" => NULL);
$stapler = array("Price" => "6.40", "Description" =>"Streamline stapler - black", "Quantity" => NULL,
"Total" => NULL);
$staples = array("Price" => "2.00", "Description" =>"Streamline staples, 5000 count", "Quantity" => NULL,
"Total" => NULL);
$products = array("Pencils" => $pencils, "Pens" => $pens, "Paper" => $paper, "Stapler" => $stapler,
"Staples" => $staples);
//doesn't work right doesn't have updated values
//Uses the array to create a text file and saves it to the hard drive in a folder entitled "/OnlineOrders"
if(isset($_POST['submit'])){
global $products;
$Dir = "OnlineOrders";
if (is_dir($Dir)){
echo "Products in order";
//print_r($products); //prints out the array as it was declared not modified!
$SaveString = "Online Order\r\n\r\n";
$SaveString .= date('m/d/Y') . "\r\n\r\n";
$SaveString .= "Item\t\tPrice\t Quantity\tTotal\r\n";
for ($i = 0; $i < count($products); ++$i){
$name = key($products);
// if ($products[$name]['Quantity']>0){
$SaveString .= $name ."\t\t" . $products[$name]['Price'] ."\t\t". $products[$name]['Quantity'] .
"\t" . $products[$name]['Total'] ."\r\n\r\n";
// }
// else
// echo "Nothing to write to file";
next($products);
}
$TimeStamp = date('Y_m_d_G_i');
$SaveFileName = "$Dir/order.$TimeStamp.txt";
$fp = fopen($SaveFileName, "wb");
if ($fp === FALSE){
echo "There was an error creating \"" . htmlentities($SaveFileName) . "\".<br />\n";
}
else {
if (flock($fp, LOCK_EX)) {
if (fwrite($fp, $SaveString)>0)
echo "Successfully wrote to file \"" . htmlentities($SaveFileName) . "\".<br />\n";
else
echo "There was an error writing to file \"" . htmlentities($SaveFileName) . "\".<br />\n";
flock($fp, LOCK_UN);
}
else{
echo "There was an error locking file \"" . htmlentities($SaveFileName) .
" for writing\".<br />\n";
}
fclose($fp);
}
}
echo "<p><a href='OnlineOrders.php'>Order Again?</p>\n";
}
//enter values into the quantity input items and addes qty and total to array and redisplays the html table with updated values
else if(isset($_POST['calc'])){
global $products;
$quantity = $_POST['quantity'];
if(is_array($quantity)){
foreach ($quantity as $item => $value){
if($value <> NULL){
$amount = stripslashes($value);
if(is_numeric($amount) && ($amount > 0)){
$products[$item]['Quantity'] = $amount;
$products[$item]['Total'] = ($products[$item]['Price'] * $amount);
}
else
echo "<p>You must enter a number greater than 0 for $item's quantity</p>\n";
}
}
DisplayTable();
//print_r($products); //TEST - PRINTS OUT THE ARRAY WITH UPDATED VALUES CORRECTLY
//TESTING STARTS HERE - SAME CODE FROM submit button and it works
$Dir = "OnlineOrders";
if (is_dir($Dir)){
$SaveString = "Online Order\r\n\r\n";
$SaveString .= date('m/d/Y') . "\r\n\r\n";
$SaveString .= "Item\t\tPrice\t Quantity\tTotal\r\n";
reset($products);
for ($j = 0; $j < count($products); ++$j){
$name = key($products);
if ($products[$name]['Quantity']>0){
$SaveString .= $name ."\t\t" . $products[$name]['Price'] ."\t\t". $products[$name]['Quantity'] .
"\t" . $products[$name]['Total'] ."\r\n";
}
next($products);
}
$TimeStamp = date('Y_m_d_G_i');
$SaveFileName = "$Dir/order.$TimeStamp.txt";
$fp = fopen($SaveFileName, "wb");
if ($fp === FALSE){
echo "There was an error creating \"" . htmlentities($SaveFileName) . "\".<br />\n";
}
else {
if (flock($fp, LOCK_EX)) {
if (fwrite($fp, $SaveString)>0)
echo "Successfully wrote to file \"" . htmlentities($SaveFileName) . "\".<br />\n";
else
echo "There was an error writing to file \"" . htmlentities($SaveFileName) . "\".<br />\n";
flock($fp, LOCK_UN);
}
else{
echo "There was an error locking file \"" . htmlentities($SaveFileName) .
" for writing\".<br />\n";
}
fclose($fp);
}
}
//Testing Ends Here
}
}
else
DisplayTable();
?>
</body>
</html>
My programming "GOD" classmate who isn't even in my class educated me on how PHP and server-side processing works. Basically, the Array does not live once you finish the processing. When the page reloads, the default array is re-created with the default NULL values. I created several functions and run the calculations for both the Calc button and Order buttons and amen it works correctly.