I have complaint.csv file in which data is like below:
1,complaint of health
2,complaint of money
.
.
.
71,complaint of bill
I want to show above data in four columns in PHP such that each column will have equal numbers of rows.
I have tried below code in which I couldn't able to get success.
<?php
$fp = file('../complaint.csv', FILE_SKIP_EMPTY_LINES);
$total_rows = count($fp);
$count = $total_rows;
$first_col = ceil($count/ 4);
$count -= $first_col;
$second_col = ceil($count/ 3);
$count -= $second_col ;
$third_col = ceil($count/ 2);
$forth_col = $count - $third_col ;
while (!feof($fp)) {
$lines[] = fgetcsv($fp, 1024);
}
fclose($fp);
?>
<div class="added">
<div class="column-left">
<?php
for ($i = 0; $i < $first_col; $i++)
{
foreach ( $lines as $line):
?>
<label class="checkbox" for="<?php print 'checkbox'.$line[$i][0]; ?>" style="font-size:20px;">
<input type="checkbox" name="complaint" value="<?php print $line[$i][0]; ?>" id="<?php print 'checkbox'.$line[$i][0]; ?>" data-toggle="checkbox">
<?php print $line[$i][1]; ?>
</label>
<?php
endforeach;
}
?>
</div>
<div class="column-center">
<?php
$k = $i;
for ($j = 0; $j < $second_col; $j++)
{
foreach ( $lines as $line):
?>
<label class="checkbox" for="<?php print 'checkbox'.$line[$j][0]; ?>" style="font-size:20px;">
<input type="checkbox" name="complaint" value="<?php print $line[$j][0]; ?>" id="<?php print 'checkbox'.$line[$j][0]; ?>" data-toggle="checkbox">
<?php print $line[$j][1]; ?>
</label>
<?php
endforeach;
$k++;
}
?>
</div>
<div class="column-center-right">
<?php
$m = $k;
for ($l = 0; $l < $third_col; $l++)
{
foreach ( $lines as $line):
?>
<label class="checkbox" for="<?php print 'checkbox'.$line[$l][0]; ?>" style="font-size:20px;">
<input type="checkbox" name="complaint" value="<?php print $line[$l][0]; ?>" id="<?php print 'checkbox'.$line[$l][0]; ?>" data-toggle="checkbox">
<?php print $line[$l][1]; ?>
</label>
<?php
endforeach;
$m++;
}
?>
</div>
<div class="column-right">
<?php
$n = $k;
for ($p = 0; $p < $forth_col; $p++)
{
foreach ( $lines as $line):
?>
<label class="checkbox" for="<?php print 'checkbox'.$line[$p][0]; ?>" style="font-size:20px;">
<input type="checkbox" name="complaint" value="<?php print $line[$p][0]; ?>" id="<?php print 'checkbox'.$line[$p][0]; ?>" data-toggle="checkbox">
<?php print $line[$p][1]; ?>
</label>
<?php
endforeach;
$n++;
}
?>
<br/>
</div>
</div>
CSS
<style>
.column-left{ float: left; width: 25%; }
.column-right{ float: right; width:25%; }
.column-center{ float: left; width: 25%; }
.column-center-right{ float: left; width: 25%; }
div.added {
padding: 0px 0px 5px 0px;
font-size: 22px;
font-family: "freightbook";
color: #2a4753;
text-align: left;
}
</style>
I am getting Error like Notice: Uninitialized string offset. The affected lines are between foreach loop
Can anyone please tell me, what went wrong in above code or any other solution of it?
Here's a solution:
Variable number of columns
Unequal number of lines are filled from left to right
Formatting of HTML elements thru styles (CSS)
Input (complaint.csv)
1,complaint of health
2,complaint of money
3,complaint type 3
4,complaint type 4
5,complaint type 5
6,complaint type 6
7,complaint type 7
8,complaint type 8
9,complaint of bill
Code
<?php
// Setup ---------------------------------------------------------------
define('numcols',4); // set the number of columns here
$csv = array_map('str_getcsv', file('./complaint.csv'));
$numcsv = count($csv);
$linespercol = floor($numcsv / numcols);
$remainder = ($numcsv % numcols);
// Setup ---------------------------------------------------------------
// Page, part 1 --------------------------------------------------------
echo '<html
<head>
<style type="text/css">
BODY { font-family:tahoma,arial,helvetica,sans-serif; font-size:76%; }
.table { background-color: #e0e0e0; }
.break { break:both; border:0; with:1px; }
.column { border:0; float:left; padding:0.333em; }
</style>
</head>
<body>
';
// Page, part 1 --------------------------------------------------------
// The n-column table --------------------------------------------------
echo '<div class="table">'.PHP_EOL;
echo ' <div class="column">'.PHP_EOL;
$lines = 0;
$lpc = $linespercol;
if ($remainder>0) { $lpc++; $remainder--; }
foreach($csv as $item) {
$lines++;
if ($lines>$lpc) {
echo ' </div>' . PHP_EOL . '<div class="column">'.PHP_EOL;
$lines = 1;
$lpc = $linespercol;
if ($remainder>0) { $lpc++; $remainder--; }
}
echo ' <label class="checkbox" for="checkbox'.$item[0].'" style="font-size:20px;">
<input type="checkbox" name="complaint" value="'.$item[0].'" id="'.$item[0].'" data-toggle="checkbox">'
.$item[1].
'</label><br />';
}
echo ' </div>'.PHP_EOL;
echo '</div>'.PHP_EOL;
// The n-column table --------------------------------------------------
// Page, part 2 --------------------------------------------------------
echo '</body>
</html>
';
// Page, part 2 --------------------------------------------------------
?>
Result
Hope this will help you. By using the PHP inbuilt SPL classes.
<?php
$file = new SplFileObject("./FL_insurance_sample.csv", "r");
$file->setFlags(SplFileObject::READ_CSV);
$file->seek($file->getSize());
$linesTotal = $file->key();
$recordsInColumn = floor($linesTotal / 4);
$res = array();
foreach ($file as $line) :
$res[] = $line;
endforeach;
$finalRecord = array_chunk($res, $recordsInColumn);
$classNames = array('column-left','column-right','column-center','column-center-right');
foreach ($finalRecord as $key => $data) : ?>
<div class="<?php echo $classNames[$key]; ?>">
<?php foreach ($data as $key1 => $row) :
if ($row[0] !== null && $row[1] !== null):
?>
<label class="checkbox" for="<?php print 'checkbox' . $row[0]; ?>" style="font-size:20px;">
<input type="checkbox" name="complaint" value="<?php print $row[0]; ?>" id="<?php print 'checkbox' . $row[0]; ?>" data-toggle="checkbox">
<?php print $row[1]; ?>
</label>
<?php
endif;
endforeach; ?>
</div>
<?php endforeach;
?>
Related
Basically it's supposed to get the user submitted value of the array size, and the method they want to calculate with the array from the drop down. the php successful gets the code from the array size but always sees the field with the dropdown as "mean" no matter which I select.
forms5.html:
`<html>
<head>
</head>
<body style="background-color: rgb(192, 192, 192);">
<div class="container" style="background-color: rgb(165, 165, 165); width: 575px; height: 250px; border: ridge; border-color: rgb(209, 209, 209);">
<form name = "form1" method = "get" action = "actions_5.php">
<div class = "form-group" style=" padding-left: 10px; padding-right: 10px; padding-top: 10px;">
<label><h2>Enter size of an array</h2></label> <br>
<input type = "number" name = "array_size" placeholder="Type in an integer">
</div>
<br>
<div style="padding-left: 10px; padding-right: 10px;">
<label><b>Select an option</b></label>
<select name = "option" class="form-control">
<option value="mean">Calculate Mean</option>
<option value="median">Calculate Median</option>
<option value="mode">Calculate Mode</option>
</select>
</div>
<div style="padding: 10px;">
<input type="submit" class="btn btn-primary">
</div>
</form>
</div>
</body>
</html>'
actions_5.php:
'<?php
session_start();
echo "<html>";
echo "<head>";
echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
';
echo "</head>";
echo "<body style='background-color: lightgray'>";
//store variables
$choice = $_GET['option'];
$size = $_GET['array_size'];
//create array
for($i = 0; $i < $size; $i++) {
$array[$i] = mt_rand(1,10);
}
echo "<div style = 'color: green; padding-top: 160px'><center><h3>Initialized array --><h3></center></div>";
echo "<br>";
echo"<center><div style = 'color: red; font-size: 35px; padding-top: 10px'>";
for($i = 0; $i < $size; $i++) {
echo"<b>$array[$i] </b>";
}
echo"</div></center>";
echo"<br>";
//if statements
echo"<center><div style = padding=top: 10px; front-size: 35px>";
if($choice = "mean") {
$mean = array_sum($array) / count($array);
echo"<p style = 'color:crimson'><b>Mean = $mean</b></p>";
} else if($choice = "mode") {
sort($array);
sort($array, $size);
$max = 1;
$mode = $array[0];
$current = 1;
for($i = 0; $i < $size; $i++){
if($array[$i] == $array[$i] - 1){
$current++;
}
else {
if($current > $max) {
$max = $current;
$mode = $array[$i - 1];
}
$current = 1;
}
}
if($current > $max) {
$max = $current;
$mode = $array[$size - 1];
}
if($max = 1) {
echo"<p style = 'color:teal'><b>There is no mode in the set.</b></p>";
} else{
echo"<p style = 'color:teal'><b>Mode = $mode</b></p>";
}
} else {
rsort($array);
$n = count($array) / 2;
$median = $array($n);
echo"<p style = 'color:blue'><b>Median = $median</b></p>";
}
echo"</div></center>";
echo "</body>";
echo "</html>";
?>'
I have a problem with displaying images in carousel. I want to display 2 images per carousel slide. I took images from database using while loop to create slides. The problem is that with my code it only displays one image per slide.
This is how it looks now:
Check the image
<?php
$brojacPoStrani = 0;
$sqlIzvestaji = mysqli_query($con, "SELECT operacije.nazivEng, izvestaji.operacija, izvestaji.ucinak, izvestaji.id FROM izvestaji INNER JOIN operacije ON izvestaji.operacijaId=operacije.id WHERE projekatId='$projekatId' AND datum='$datum'");
while ($row = mysqli_fetch_array($sqlIzvestaji)) {
$id = $row['id'];
$sqlSlike = mysqli_query($con, "SELECT img_name FROM slike WHERE izvestajId='$id' AND datum='$datum'");
$brojacDuplikata = false;
while ($row2 = mysqli_fetch_array($sqlSlike)) {
if ($brojacPoStrani % 2 == 0) {
?>
<div class="carousel-cell" style="background-image: url('img/izvestaji.jpg'); background-repeat: no-repeat; background-size: 100% 350px;">
<h1 style="color: #fff; text-align: left; padding-left: 15px; font-weight: bold;"><?php echo $row['nazivEng']; ?></h1>
<?php
if ($brojacDuplikata === false) {
$brojacDuplikata = true;
?>
<p style="text-align: left; padding-left: 45px; padding-top: 20px; padding-bottom: 10px;"><?php echo $row['operacija'] . " - " . $row['ucinak']; ?></p>
<?php
} else {
?>
<p style="text-align: left; padding-left: 45px; padding-top: 40px; padding-bottom: 10px;"></p>
<?php
}
?>
<div class="row">
<?php
if ($brojacPoStrani % 2 == 0) {
?>
<div class="col-lg-6">
<img src="../files/izvestaji/<?php echo $project; ?>/<?php echo $datum; ?>/<?php echo $row['nazivEng']; ?>/<?php echo $row2['img_name']; ?>" style="width: 350px; height: 350px; padding-left: 10px;" class="float-right" />
</div>
<?php
} else {
?>
<div class="col-lg-6">
<img src="../files/izvestaji/<?php echo $project; ?>/<?php echo $datum; ?>/<?php echo $row['nazivEng']; ?>/<?php echo $row2['img_name']; ?>" style="width: 350px; height: 350px; padding-right: 10px;" class="float-left" />
</div>
<?php
}
?>
</div>
<br />
</div>
<?php
}
$brojacPoStrani++;
}
$brojacPoStrani = 0;
}
As mentioned it looks like you should be able to use a single query rather than having nested queries - and to display 2 images per carousel slide you effectively want to select data from the current and next rows. One easy way to do that would be to assign the entire recordset to a variable and then process that array using a for loop. The following is a simplified, semi-pseudo code version that attempts to combine the sql queries and assign recordset to an array. It is not tested as such but it might? be of use.
$sql="select
o.naziveng,
i.operacija,
i.ucinak,
i.id,
s.img_name
from izvestaji i
inner join operacije o on i.operacijaid=o.id
inner join slike s on s.izvestajId=i.id
where projekatid='$projekatid' and datum='$datum'";
$res = mysqli_query( $con, $sql );
if( $res ){
$arr = mysqli_fetch_all( $res, MYSQLI_BOTH );
for( $i=0; $i < count( $arr ); $i+=2 ){
try{
$r1=array_key_exists( $i+0, $arr ) ? $arr[ $i+0 ] : false;
$r2=array_key_exists( $i+1, $arr ) ? $arr[ $i+1 ] : false;
/*
generate the HTML structure and add two images
*/
echo '<div class="carousel-cell">'; # simplified version
if( $r1 )echo 'row 1: '.$r1['img_name'];
if( $r2 )echo 'row 2: '.$r2['img_name'];
echo '</div>';
}catch( Exception $e ){
continue;
}
}
}
I want show checkbox as a grid without scrolling the page. I am developing a attendance reporting page which shows student name and checkbox with values from database. I want to show its in a grid like this:
My code shows like this:
My code:
<table border="1" cellspacing="2" cellpadding="5" summary="">
<?php
while ($row = mysql_fetch_assoc($res)){?>
<th>
<input type="checkbox" class="input" id="input
<?php echo $row['st_id']; ?>"
name="student[]" value="<?php echo $row['st_id']; ?>"
checked="checked" >
<?php echo $row['st_name'] ; ?>
<label for="input<?php echo $row['st_id']; ?>">
</label>
</th>
This code take both name and checkbox id from the database..Anybody please help
You can use floating DIVs instead of table:
<style>
.inputDiv{
float: left;
padding: 5px;
margin: 5px;
border: 1px solid black;
}
</style>
<?php while ($row = mysql_fetch_assoc($res)) { ?>
<div class="inputDiv">
<input type="checkbox" class="input" id="input<?php echo $row['st_id']; ?>" name="student[]" value="<?php echo $row['st_id']; ?>" checked="checked" > <?php echo $row['st_name']; ?>
<label for="input<?php echo $row['st_id']; ?>"></label>
</div>
<?php } ?>
This will reorder automatically all DIVs depending of user's screen resolution.
You can use it like this:
<table border="1" cellspacing="2" cellpadding="5" summary="">
<?php
$counter = 1;
while ($row = mysql_fetch_assoc($res)){
if($number==1 ) {
echo '<tr>';
}
if($number %6 == 0) {
echo '</tr><tr>';
}
?>
<th> <input type="checkbox" class="input" id="input<?php echo $row['st_id']; ?>" name="student[]" value="<?php echo $row['st_id']; ?>" checked="checked" > <?php echo $row['st_name'] ; ?> <label for="input<?php echo $row['st_id']; ?>"></label></th>
<?php
$counter++;
if($number==0 || $number %6 == 0) {
echo '</tr>';
}
}
?>
</tr>
</table>
I want to check the equality of the "$v" and "$formats2". But it gives and error message
Warning: strcmp() expects parameter 2 to be string, array given in C:\xampp\htdocs\playit2\product.php on line 312
Here is my HTML code.
$jsqla = mysql_query("select * from products where id='$product_id'") or die(mysql_error());
$jfeta = mysql_fetch_assoc($jsqla);
$formats = explode(";", $jfeta['formats']);
$jsqla2 = mysql_query("select formats from request_list where id='$product_id'") or die(mysql_error());
$jfeta2 = mysql_fetch_assoc($jsqla2);
$formats2 = explode(";", $jfeta2['formats']);
<div class="">
<?php if($formats2 != "") { ?>
<?php foreach($formats as $v){ ?>
<label style="line-height: 1.25em;display: block;width: 100px;margin-right: 10px;float: left;">
<div id="format-id_<?php echo $v?>" <?php if (strcmp($v, $formats2) === 0) { ?> style="border: 1px solid;border-radius: 9px;text-align: center;padding-top: 10px;padding-bottom:10px;padding-left: 3px;padding-right: 3px;border-color: #cccccc;font-family: 'SSemibold'; font-size: 13px; color: #44b7da; background-color: #cccccc;" <?php } else { ?> style="border: 1px solid;border-radius: 9px;text-align: center;padding-top: 10px;padding-bottom:10px;padding-left: 3px;padding-right: 3px;border-color: #cccccc;font-family: 'SSemibold'; font-size: 13px; color: #44b7da;" <?php } ?>>
<input class="format_cheks" type="radio" value="<?php echo $v; ?>" name="abc" style="visibility:hidden;" id="<?php echo $v ?>" onClick="changeColour(this)"/>
<span style="margin:-17px auto auto 0px;display:block;"><?php echo $v; ?></span>
</div>
</label>
<?php } ?>
<?php } else { ?>
<?php foreach($formats as $v){ ?>
<label style="line-height: 1.25em;display: block;width: 100px;margin-right: 10px;float: left;">
<div id="format-id_<?php echo $v?>" style="border: 1px solid;border-radius: 9px;text-align: center;padding-top: 10px;padding-bottom:10px;padding-left: 3px;padding-right: 3px;border-color: #cccccc;font-family: 'SSemibold'; font-size: 13px; color: #44b7da;">
<input class="format_cheks" type="radio" value="<?php echo $v; ?>" name="abc" style="visibility:hidden;" id="<?php echo $v ?>" onClick="changeColour(this)"/>
<span style="margin:-17px auto auto 0px;display:block;"><?php echo $v; ?></span>
</div>
</label>
<?php } ?>
<?php } ?>
</div>
You mistyped implode as explode. The latter takes a string and produces an array. You likely want the opposite. UPD: Oh, you already have a string. Then simply use it as is:
- $formats2 = explode(";", $jfeta2['formats']);
+ $formats2 = $jfeta2['formats'];
Hope it helps.
You also use
if( $val1 === $val2){
//true part . this === strictly check
}
You should pass the key as after explode it will contain an array.
strcmp($v, $formats2[key])
explode()
I have the following form in php, but I want to make the insert.php action, to insert everything in a new row in MySQL... I don't know how to do it, because there are several fieldsets, it's easy with one simple form, but not for each $_cliente and $_servicio
CODE UPDATE
<?php
require("database.class.php");
//database server
define('DB_SERVER', "localhost");
//database usuario
define('DB_USER', "root");
//database password
define('DB_PASS', "root");
define('DB_DATABASE', "nivelservicio");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$db->connect();
$sql = "SELECT * FROM servicios";
$_row = $db->query($sql);
$_servicios = array();
while($row = $db->fetch_array($_row)) {
$_servicios[$row['id']] = $row['nombre'];
}
$sql = "SELECT * FROM clientes";
$_row = $db->query($sql);
$_clientes = array();
while($row = $db->fetch_array($_row)) {
$_clientes[$row['id']] = $row['nombre'];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<style>
body{
margin:0;
border:0;
}
#formfieldset{
width: 350px;
font-family: helvetica, sans-serif, verdana;
font-size:12px;
}
h1 {
font-size:36px;
font-family: Georgia;
font-style: italic;
border-bottom:1px solid #000;
}
h2 {
font-size:18px;
font-color:#1E1E1E;
}
</style>
</head>
<body>
<form action="insert.php" method="post">
<div id="formfieldset">
<?php foreach ($_clientes as $key_cliente => $cliente) :
switch ($cliente) {
case "Produban":
$_servicios = array_diff($_servicios, array(
"GESTI",
"VULCANO"
));
break;
} ?>
<h1><?php echo $cliente ?></h1>
<input type='hidden' name='cliente_id[<?php echo $key_cliente ?>' value='<?php echo $key_cliente ?>'>
<?php foreach($_servicios as $key_servicio => $servicio) : ?>
<h2><?php echo $servicio ?></h2>
<input type="hidden" name="servicio_id[<?php echo $key_cliente ?>][<?php echo $key_servicio ?>]" value="<?php echo $key_servicio; ?>">
<label>Estado</label>
<select name="estado[<?php echo $key_cliente ?>][<?php echo $key_servicio ?>">
<option value="OK">OK</option>
<option value="KO">KO</option>
</select>
<label>Texto</label><input type="text" name="texto">
<?php endforeach; ?>
<?php endforeach; ?>
<br>
<input type="submit" name="insertar" value="Insertar">
</div>
</form>
</body>
</html>
<?php
$db->close();
?>
insert.php
if(isset($_POST['insertar'])){
var_dump($_POST);
foreach ($clientes as $key_cliente => $cliente) {
foreach ($servicios as $key_servicio => $servicio) {
//echo $_POST['estado'][$key_cliente][$key_servicio] . '<br />';
$sql = "INSERT INTO datos
(servicio_id, cliente_id, estado, texto, fecha)
VALUES
('".$_POST['servicio_id'][$key_cliente][$key_servicio]."',
'".$_POST['cliente_id'][$key_cliente][$key_servicio]."',
'".$_POST['estado'][$key_cliente][$key_servicio]."',
'".$_POST['texto'][$key_cliente][$key_servicio]."',
'".date('d-m-Y')."'
)";
$db->query($sql);
}
}
echo "Valores insertados";
}
You need to change the name of your input fields to arrays like this:
<select name="estado[]">
And then in your PHP you can do this:
<?php
foreach ($_POST['estatdo'] as $key => $val) {
echo $_POST['estatdo'][$key] . ' - ' echo $_POST['texto'][$key] . ' - ' echo $_POST['servicio_id'][$key] . '<br />';
}
Here's a full example:
<form action="insert.php" method="post">
<div id="formfieldset">
<?php foreach ($_clientes as $key_cliente => $cliente) :
switch ($cliente) {
case "Produban":
$_servicios = array_diff($_servicios, array(
"GESTI",
"VULCANO"
));
break;
} ?>
<h1><?php echo $cliente ?></h1>
<input type='hidden' name='cliente_id[<?php echo $key_cliente ?>]' value='<?php echo $key_cliente ?>'>
<?php foreach($_servicios as $key_servicio => $servicio) : ?>
<h2><?php echo $servicio ?></h2>
<input type="hidden" name="servicio_id[<?php echo $key_cliente ?>][<?php echo $key_servicio ?>]" value="<?php echo $key_servicio; ?>">
<label>Estado</label>
<select name="estado[<?php echo $key_cliente ?>][<?php echo $key_servicio ?>]">
<option value="OK">OK</option>
<option value="KO">KO</option>
</select>
<label>Texto</label><input type="text" name="texto">
<?php endforeach; ?>
<?php endforeach; ?>
<br>
<input type="submit" name="insertar" value="Insertar">
</div>
</form>
So in this example we have a double nested array so instead of estado[] we have estado[][]. Also instead of using [] which makes an array with consecutive numeric keys (i.e., 0, 1, 2, 3) I've changed it to use the client id and the service id like this:
<select name="estado[<?php echo $key_cliente ?>][<?php echo $key_servicio ?>]>
And then in your php you can loop through it like this:
foreach ($clientes as $key_cliente => $cliente) {
foreach ($servicios as $key_servicio => $servicio) {
echo $_POST['estado'][$key_cliente][$key_servicio] . '<br />;
}
}