PHP Form submit with arrays as rows - php

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 />;
}
}

Related

works fine in WAMP but doesn't work in XAMPP

I have the following code in my program that works perfectly with the WAMP server. But I had to change the WAMP server for XAMPP and I don’t know why it doesn’t execute some parts of the code. There’s also no error message.
The problem is that in the table code <table>, it doesn’t show after the third <tr> or when the 'Toggle' starts. It also doesn’t show the submit button.
I don’t understand why everything works correctly in WAMP but not in XAMPP. Can someone help me see why it fails? Thank you
Project.php
<?php
include_once("Conexion.php");
include_once("functions.php");
ob_start();
$_SESSION['ex_time'] = date('Y-m-d H:i:s');
$list_ex = array();
$result = doSearch($conn);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styleProject.css">
</head>
<body>
<div id="centered_A">
<form action='' method='post'>
<table id="exercises">
<tr>
<th colspan="3"><h2>Exercises</h2></th>
</tr>
<tr>
<th><h3>Exercise_ID</h3></th>
<th><h3>Title</h3></th>
<th><h3>Difficulty
<form id="difficulty_form" method="get">
<select id="filter" name="filter" onchange="document.getElementById('difficulty_form').submit()">
<option value="All">Todas</option>
<?php
for ($i = 1; $i <= 5; $i++) {
$selected = '';
if (isset($_GET['filter']) && $_GET['filter'] == $i) {
$selected = ' selected';
}
echo "<option value=\"$i\"$selected>$i</option>\n";
}
?>
</select>
</form>
</h3></th>
</tr>
<?php
$order = 1;
$num_ex = 1;
while($row = $result->fetch_assoc())
{
array_push($list_ex, $row["exercise_id"]);
$sql_check_ex = "select * from answers a where a.student_id=".$_SESSION['user_id']." and a.exercise_id_fk=".$row["exercise_id"].";";
$result_check_ex = $conn->query($sql_check_ex);
?>
<tr>
<td><?php echo $num_ex; ?></td>
<!---Click Toggle Exercise-->
<td><a onclick="myFunction(<?php echo $row["exercise_id"] ?>)" role="button" class="btn" target="_blank" ><?php echo $row["title"]; ?></a>
</td>
<td><?php echo $row["difficulty"]; ?></td>
</tr>
<!--- Toggle --->
<tr id="toggle<?php echo $row["exercise_id"] ?>" style="display:none">
<td colspan="3">
<?php
$sql = "SELECT * FROM exercises WHERE exercise_id='".$row["exercise_id"]."'";
$result_ej = $conn->query($sql);
$row_ej = $result_ej->fetch_assoc();
?>
<p><?php $row["exercise_id"] ?> <?php echo $row["text"]?></p>
<br><!--- Radio Button --->
<?php
if ($row["type"] == 0) {
$ansarray = explode("\n", $row["image_path"]);
$randomans = [];
for($i=0; $i<count($ansarray); $i++) {
$a = array($i+1, $ansarray[$i]);
array_push($randomans, $a);
}
shuffle($randomans);
for($i=0; $i<count($randomans); $i++) {
echo "<div class=\"radio\" style=\"text-align:left; display:flex; vertical-align: baseline;\">";
echo "<input type=\"radio\" style=\"margin-top: 8px; cursor:pointer;\" name=\"choice".$row["exercise_id"]."\" value= \"".$randomans[$i][0]."\" />".$randomans[$i][1]."<br>";
echo "</div>";
}
echo "<input type=\"text\" name=\"choicetext".$row["exercise_id"]."\" value='multi' style=\"display:none;\">";
} else {
?>
<input type="radio" style="margin-top: 8px" name="choice<?php echo $row["exercise_id"] ?>" value= "0" checked="checked" style="display:none;" />
<?php
}
?>
<br>
<!--- Select level --->
<p2>Select difficulty level:</p2>
<select name="choose<?php echo $row["exercise_id"] ?>" id="choose<?php echo $row["exercise_id"] ?>">>
<option value="1" <?php if($row["difficulty"]=="1") { echo "selected"; } ?> >1</option>
<option value="2" <?php if($row["difficulty"]=="2") { echo "selected"; } ?> >2</option>
</select>
</td>
</tr><!---Finish Toggle --->
<?php
$order++;
$num_ex++;
}
?>
</table>
<br><!---Submit Button-->
<input class="buttonSubmit" type="submit" name="submit_proj_ex" value="Submit">
</form>
<script>
function myFunction(ejer_id) {
var x = document.getElementById("toggle" + ejer_id);
if (x.style.display === "none") {
x.style.display = "table-row";
} else {
x.style.display = "none";
}
}
</script>
</div>
</body>
<?php
if (isset($_POST['submit_proj_ex'])) {
include_once("store_answers.php");
header('location: Results.php');
}
?>
</html>
functions.php
<?php
function doSearch($conn, $fields = "*") {
$sql = "SELECT $fields FROM exercises, ex_tag, tags where exercise_id = exercise_id_fk and tag_id = tag_id_fk";
if (isset($_GET['filter']) && $_GET['filter'] !== 'All') {
$filter = (int) trim($_GET['filter']);
$sql .= " and exercises.difficulty = '$filter'";
}
if (!empty($_SESSION['tags_array'])) {
$sql .= " and (";
foreach ($_SESSION['tags_array'] as $tagId)
$sql .= 'tag_id = ' . $tagId . ' or ';
$sql .= "tag_id = -1)";
}
$sql .= ' group by exercise_id_fk';
return $conn->query($sql);
}
?>
Run phpinfo() in both WAMP and XAMP. I'm not certain what your issue is, but if it works in one and not the other, perhaps they are using different versions of php. If this is the case, you will need to use the same version of php in your XAMP as you were using in WAMP, or go through your code and try to figure out how to convert your code, such that it works correctly with the version on your XAMP. The former is probably the path of least resistance.

How to insert data from shopping cart into the DB

I made simple shopping cart using PHP for my website, so now I need to take data from that shopping cart and the form and send it to the DB. I tried writing the code myself but it doesn't work, when I press the submit button nothing happens. What could be the problem?
This is the code I have:
Index.php:
<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "tut");
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Top Food-Porucivanje za firme</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div class="container" style="width:60%;">
<h2 align="center">Top Food kolica</h2>
<br />
<form>
<input type="textbox" name="ime_firme" placeholder="Ime firme">
<input type="textbox" name="ime" placeholder="Ime">
<input type="textbox" name="prezime" placeholder="Prezime">
</form>
<br />
<br />
<?php
$query = "SELECT `id`, `p_name`, `image`, `price` FROM `products` WHERE 1";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<div class="col-md-3">
<form method="post" action="shop.php?action=add&id=<?php echo $row["id"]; ?>">
<div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">
<img src="<?php echo $row["image"]; ?>" class="img-responsive">
<h5 class="text-info"><?php echo $row["p_name"]; ?></h5>
<h5 class="text-danger"> <?php echo $row["price"]; ?> RSD</h5>
<input type="text" name="quantity" class="form-control" value="1">
<input type="hidden" name="hidden_name" value="<?php echo $row["p_name"]; ?>">
<input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>">
<input type="submit" name="add" style="margin-top:5px;" class="btn btn-default" value="Dodaj u kolica">
</div>
</form>
</div>
<?php
}
}
?>
<div style="clear:both"></div>
<h2>Moja kolica</h2>
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="40%">Ime proizvoda</th>
<th width="10%">Kolicina</th>
<th width="20%">Cena</th>
<th width="15%">Ukupno</th>
<th width="5%">Komanda</th>
</tr>
<?php
if(!empty($_SESSION["cart"]))
{
$total = 0;
foreach($_SESSION["cart"] as $keys => $values)
{
?>
<tr>
<td name="ime"><?php echo $values["item_name"]; ?></td>
<td><?php echo $values["item_quantity"] ?> X</td>
<td> <?php echo $values["product_price"]; ?> RSD</td>
<td> <?php echo number_format($values["item_quantity"] * $values["product_price"], 2); ?> RSD</td>
<td><span class="text-danger">Ukloni</span></td>
</tr>
<?php
$total = $total + ($values["item_quantity"] * $values["product_price"]);
}
?>
<tr>
<td colspan="3" align="right">Ukupno</td>
<td align="right"> <?php echo number_format($total, 2); ?> RSD</td>
<td></td>
</tr>
<?php
}
?>
</table>
<input type="submit" value="Poruci">
</div>
</div>
</body>
</html>
Shop.php:
<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "tut");
if(isset($_POST["add"]))
{
if(isset($_SESSION["cart"]))
{
$item_array_id = array_column($_SESSION["cart"], "product_id");
if(!in_array($_GET["id"], $item_array_id))
{
$count = count($_SESSION["cart"]);
$item_array = array(
'product_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'product_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["cart"][$count] = $item_array;
echo '<script>window.location="index.php"</script>';
}
else
{
echo '<script>alert("Proizvod je vec u kolicima")</script>';
echo '<script>window.location="index.php"</script>';
}
}
else
{
$item_array = array(
'product_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'product_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["cart"][0] = $item_array;
}
}
if(isset($_GET["action"]))
{
if($_GET["action"] == "delete")
{
foreach($_SESSION["cart"] as $keys => $values)
{
if($values["product_id"] == $_GET["id"])
{
unset($_SESSION["cart"][$keys]);
echo '<script>alert("Proizvod je uklonjen")</script>';
echo '<script>window.location="index.php"</script>';
}
}
}
}
?>
My attempt at sending data into the database:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tut";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tut (p_name, image, price)
VALUES ('{$mysqli->real_escape_string($_POST['ime'])}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
submit button is placed outside the form tag, make sure your data is submitted

Shopping Cart only enters last item in Database not all of the data

I am having an issue with my shopping cart when I add three items only the last item enters into the database. I am not sure how to get all the items to insert into the database like 3 or 4. I have tried many different ways and still come up with nothing. I still have to also figure how to get subtotal and customer name to attach to the orders
Index.php
<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM tblproduct WHERE code='" . $_GET["code"] . "'");
$itemArray = array($productByCode[0]["code"]=>array('name'=>$productByCode[0]["name"], 'code'=>$productByCode[0]["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["code"],array_keys($_SESSION["cart_item"]))) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["code"] == $k) {
if(empty($_SESSION["cart_item"][$k]["quantity"])) {
$_SESSION["cart_item"][$k]["quantity"] = 0;
}
$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
}
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;
case "remove":
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($_GET["code"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
}
?>
<HTML>
<HEAD>
<TITLE>Simple PHP Shopping Cart</TITLE>
<link href="style.css" type="text/css" rel="stylesheet" />
</HEAD>
<BODY>
<div id="product-grid">
<div class="txt-heading">Products</div>
<?php
$product_array = $db_handle->runQuery("SELECT * FROM tblproduct ORDER BY id ASC");
if (!empty($product_array)) {
foreach($product_array as $key=>$value){
?>
<div class="product-item">
<form method="post" action="index.php?action=add&code=<?php echo $product_array[$key]["code"]; ?>">
<div class="product-image"><img src="<?php echo $product_array[$key]["image"]; ?>"></div>
<div><strong><?php echo $product_array[$key]["name"]; ?></strong></div>
<div class="product-price"><?php echo "$".$product_array[$key]["price"]; ?></div>
<div><input type="text" name="quantity" value="1" size="2" /><input type="submit" value="Add to cart" class="btnAddAction" /></div>
</form>
</div>
<?php
}
}
?>
</div>
<div id="shopping-cart">
<div class="txt-heading">Shopping Cart <a id="btnEmpty" href="index.php?action=empty">Empty Cart</a></div>
<?php
if(isset($_SESSION["cart_item"])){
$item_total = 0;
?>
<form method="post" action="process_insert.php">
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th style="text-align:left;"><strong>Name</strong></th>
<th style="text-align:left;"><strong>Code</strong></th>
<th style="text-align:right;"><strong>Quantity</strong></th>
<th style="text-align:right;"><strong>Price</strong></th>
<th style="text-align:center;"><strong>Action</strong></th>
</tr>
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td style="text-align:left;border-bottom:#F0F0F0 1px solid;" ><input type="text" name="name" value="<?php echo $item["name"]; ?>"></td>
<td style="text-align:left;border-bottom:#F0F0F0 1px solid;"><input type="text" name="code" value="<?php echo $item["code"]; ?>"></td>
<td style="text-align:right;border-bottom:#F0F0F0 1px solid;"><input type="text" name="quantity" value="<?php echo $item["quantity"]; ?>"></td>
<td style="text-align:right;border-bottom:#F0F0F0 1px solid;"><input type="text" name="price" value="<?php echo $item["price"]; ?>"></td>
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;">Remove Item</td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
<tr>
<td colspan="5" align=right><strong>Total:</strong> <?php echo "$".$item_total; ?></td>
</tr>
</tbody>
</table>
<?php
}
?>
<input type="submit" name="submit" value="submit">
</form>
</div>
</BODY>
</HTML>
process_insert.php
<html>
<head>
<title></title>
</head>
<body>
<?php
ini_set('display_errors', 1);
error_reporting(~0);
$serverName = "localhost";
$userName = "root";
$userPassword = "";
$dbName = "blog_samples";
$conn = mysqli_connect($serverName,$userName,$userPassword,$dbName);
$sql = "INSERT INTO order_table (name, code, quantity, price)
VALUES ('".$_POST["name"]."','".$_POST["code"]."'
,'".$_POST["quantity"]."','".$_POST["price"]."')";
$query = mysqli_query($conn,$sql);
if($query) {
echo "Record add successfully";
}
mysqli_close($conn);
?>
</body>
</html>
That's because your submit form doesnt support multiple fields.
You have to add a index to each inputs' name.
<?php
$i = 0;
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td style="text-align:left;border-bottom:#F0F0F0 1px solid;" ><input type="text" name="name[<?php echo $i; ?>]" value="<?php echo $item["name"]; ?>"></td>
<td style="text-align:left;border-bottom:#F0F0F0 1px solid;"><input type="text" name="code[<?php echo $i; ?>]" value="<?php echo $item["code"]; ?>"></td>
<td style="text-align:right;border-bottom:#F0F0F0 1px solid;"><input type="text" name="quantity[<?php echo $i; ?>]" value="<?php echo $item["quantity"]; ?>"></td>
<td style="text-align:right;border-bottom:#F0F0F0 1px solid;"><input type="text" name="price[<?php echo $i; ?>]" value="<?php echo $item["price"]; ?>"></td>
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;">Remove Item</td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
$i++;
}
?>
process_insert.php
<html>
<head>
<title></title>
</head>
<body>
<?php
ini_set('display_errors', 1);
error_reporting(~0);
$serverName = "localhost";
$userName = "root";
$userPassword = "";
$dbName = "blog_samples";
$conn = mysqli_connect($serverName,$userName,$userPassword,$dbName);
$rows_count = count($_POST["name"]);
for($i=0;$i<$rows_count;$i++){
// PREVENTING SQL INJECTION !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$name = mysqli_real_escape_string($conn,$_POST["name"][$i]);
$code = mysqli_real_escape_string($conn,$_POST["code"][$i]);
$quantity = intval($_POST["quantity"][$i]);
$price = mysqli_real_escape_string($conn,$_POST["price"][$i]);
$sql = "INSERT INTO order_table (name, code, quantity, price)
VALUES ('$name','$code','$quantity','$price')";
$query = mysqli_query($conn,$sql);
}
if(mysqli_affected_rows($conn)>0) {
echo "Record add successfully";
}
mysqli_close($conn);
?>
</body>
</html>

Very heavy wordpress plugin and customization

i have a wordpress website and with customization (cache/minify/database), is really quick in frontend, and in backend, with one exception. I use a plugin where it stores and retrieves players stats, carreers, teams etc.
When saving the team's match player's statistics, it needs 5 minutes to show the page reloaded with the data.
Also when retrieving for example team's season data, it also needs a lot of time to show them.
From what i ve seen, it is related with two of my files that do all the work. tournament_match.php, and functions.php. From hosting they said that it gets all tha database and thats why it is so slow
Here is the tournament_match file
<?php
global $wpdb;
global $msg;
$page = $_GET['page'];
$tournament_id = $_GET['tid'];
$match_id = $_GET['mid'];
$league_type = leagueengine_fetch_data_from_id($tournament_id,'league_type');
if(isset($_POST['home_team_bonus']) or isset($_POST['away_team_bonus'])) {
if(isset($_POST['save_tournament_match'])) { leagueengine_save_tournament_match($tournament_id,$match_id,$_POST['date_alt'],$_POST['time_alt'],$_POST['home_team_id'],$_POST['away_team_id'],$_POST['home_team_score'],$_POST['away_team_score'],$_POST['home_team_bonus'],$_POST['away_team_bonus']); }
} else {
if(isset($_POST['save_tournament_match'])) { leagueengine_save_tournament_match($tournament_id,$match_id,$_POST['date_alt'],$_POST['time_alt'],$_POST['home_team_id'],$_POST['away_team_id'],$_POST['home_team_score'],$_POST['away_team_score']); }
}
if(isset($_POST['save_attributes'])) { leagueengine_save_attribute_values('tournament_match',NULL,NULL,$match_id,NULL,NULL,$tournament_id); }
if(isset($_POST['add_event_to_match'])) { error_reporting(0); leagueengine_add_event_to_tournament_match($tournament_id,$match_id,$_POST['new_event_id'],$_POST['new_event_time'],$_POST['timeline_text'],$_POST['new_event_count'],$_POST['new_event_player_id']); error_reporting(1); }
if(isset($_POST['save_events'])) { leagueengine_save_event_times('tournament_match',$_POST['event_time_id'],$_POST['event_time'],$_POST['event_text']); }
if(isset($_POST['add_home_event_to_match'])){
error_reporting(0);
foreach($_POST as $key=>$val){
$val=intval($val);
if(is_int($val)&&$val>0){
$data=explode('-',$key);
$playerid=$data[1];
$eventid=$data[2];
leagueengine_add_event_to_tournament_match2($tournament_id,$match_id,$eventid,$_POST['new_event_time'],$_POST['timeline_text'],$val,$playerid);
}
}
error_reporting(1);
}
if(isset($_POST['add_away_event_to_match'])){
error_reporting(0);
foreach($_POST as $key=>$val){
$val=intval($val);
if(is_int($val)&&$val>0){
$data=explode('-',$key);
$playerid=$data[1];
$eventid=$data[2];
leagueengine_add_event_to_tournament_match2($tournament_id,$match_id,$eventid,$_POST['new_event_time'],$_POST['timeline_text'],$val,$playerid);
}
}
error_reporting(1);
}
if(isset($_POST['save_tournament_match_lineups'])) {
if(isset($_POST['homeplayers'])) { $homeplayers = $_POST['homeplayers']; } else { $homeplayers = ''; }
if(isset($_POST['awayplayers'])) { $awayplayers = $_POST['awayplayers']; } else { $awayplayers = ''; }
if(isset($_POST['homesubs'])) { $homesubs = $_POST['homesubs']; } else { $homesubs = ''; }
if(isset($_POST['awaysubs'])) { $awaysubs = $_POST['awaysubs']; } else { $awaysubs = ''; }
leagueengine_save_tournament_match_lineups($tournament_id,$match_id,$homeplayers,$awayplayers,$homesubs,$awaysubs);
}
if(isset($_POST['delete_events'])) { leagueengine_delete_data('tournament_match_event',$_POST['delete_id'],'tournament',NULL,NULL,$tournament_id,$match_id); }
if(isset($_POST['save_match_statistics'])) { leagueengine_save_tournament_match_statistics($tournament_id,$match_id,$_POST['tournament_match_statistic'],$_POST['home_value'],$_POST['away_value'],$_POST['att_type']); }
if(isset($_POST['save_tournament_match_preview'])) { leagueengine_save_tournament_match_preview($tournament_id,$match_id,stripslashes_deep($_POST['match_preview'])); }
if(isset($_POST['save_tournament_match_report'])) { leagueengine_save_tournament_match_report($tournament_id,$match_id,stripslashes_deep($_POST['match_report'])); }
if(isset($_POST['tournament_match_swap'])) { leagueengine_tournament_match_swap($tournament_id,$match_id); }
$table = $wpdb->prefix . 'leagueengine_tournament_matches';
$match = $wpdb->get_row("SELECT * FROM $table WHERE tournament_id = '$tournament_id' AND id = '$match_id'");
$home_team_id = $match->home_team_id;
$away_team_id = $match->away_team_id;
$tournament = leagueengine_fetch_data_row('tournament',$tournament_id);
$table2 = $wpdb->prefix . 'leagueengine_tournaments';
$tournament_row = $wpdb->get_row("SELECT * FROM $table2 WHERE data_id = '$tournament_id'");
?>
<div id="leagueengine_admin" class="<?php echo $page; ?>">
<?php echo leagueengine_admin_header(); ?>
<div id="leagueengine_admin_content">
<?php if($msg) { echo $msg; } ?>
<ul class="breadcrumbs">
<li><?php _e('Competitions','leagueengine');?> <span class="divider">/</span></li>
<li><?php echo leagueengine_fetch_data_from_id($tournament_id,'data_value') ?> <span class="divider">/</span></li>
<?php if($match->round == 'GROUP') { ?>
<li><?php _e('Groups','leagueengine');?> <span class="divider">/</span></li>
<?php } else { ?>
<li><?php _e('Knockout','leagueengine');?> <span class="divider">/</span></li>
<?php } ?>
<li><?php _e('Match','leagueengine');?></li>
</ul>
<?php
if($league_type == 'players') {
$home_emblem = leagueengine_fetch_player_emblem($match->home_team_id,20);
$away_emblem = leagueengine_fetch_player_emblem($match->away_team_id,20,'right');
} else {
$home_emblem = leagueengine_fetch_team_emblem($match->home_team_id,20);
$away_emblem = leagueengine_fetch_team_emblem($match->away_team_id,20,'right');
}
?>
<div class="match_masthead">
<table>
<tr>
<td class="home_team" style="border-top: 5px solid <?php echo leagueengine_fetch_team_colour($match->home_team_id,'primary');?>; text-align:left;width:40%;"><?php echo $home_emblem . leagueengine_fetch_data_from_id($match->home_team_id,'data_value');?></td>
<td class="score" style="text-align:center;width:20%;"><span><?php echo $match->home_team_score;?> &dash; <?php echo $match->away_team_score;?></span></td>
<td class="away_team" style="border-top: 5px solid <?php echo leagueengine_fetch_team_colour($match->away_team_id,'primary');?>; text-align:right;width:40%;"><?php echo leagueengine_fetch_data_from_id($match->away_team_id,'data_value') . $away_emblem;?></td>
</tr>
<tr>
<td colspan="3" style="text-align:center;"><?php echo date(leagueengine_fetch_settings('date_format_php'),strtotime($match->match_date)) . ' ' . date(leagueengine_fetch_settings('time_format_php'),strtotime($match->match_time)); ?></td>
</tr>
<tr>
<td class="competition" colspan="3" style="text-align:center;"><?php echo '' . leagueengine_fetch_data_from_id($tournament_id,'data_value') . ''; ?></td>
</tr>
<tr><td colspan="100%" style="text-align:center;padding-bottom:20px;"><?php echo leagueengine_link('tournament_match&tid='.$tournament_id.'&mid='.$match->id,__('Go To Match','leagueengine'),'','','button-primary'); ?></td></tr>
</table>
</div>
<div id="leagueengine_tabs">
<ul>
<li><?php _e('Score','leagueengine');?></li>
<?php
$table = $wpdb->prefix . 'leagueengine_player_careers';
$homeplayers = $wpdb->get_results("SELECT * FROM $table WHERE tournament_id = '$tournament_id' AND team_id = '$home_team_id'");
$awayplayers = $wpdb->get_results("SELECT * FROM $table WHERE tournament_id = '$tournament_id' AND team_id = '$away_team_id'");
if($homeplayers or $awayplayers && $league_type != 'players') {
?>
<li><?php _e('Lineups','leagueengine');?></li>
<?php } ?>
<?php if(leagueengine_data_exists('event')) { echo '<li>' . __('Events','leagueengine') . '</li>'; } ?>
<?php if(leagueengine_statistics_exists('tournament_match')) { echo '<li>' . __('Statistics','leagueengine') . '</li>'; } ?>
<?php if(leagueengine_h2h_history($match->match_date,$home_team_id,$away_team_id)) { echo '<li>' . __('History','leagueengine') . '</li>'; } ?>
<li><?php _e('Report','leagueengine');?></li>
</ul>
<div id="score">
<form action="" method="POST">
<table class="form">
<tr>
<th style="width:20%;"><?php _e('Date/Time','leagueengine');?></th>
<th style="width:30%;text-align:center;"><?php _e('Home','leagueengine');?></th>
<th style="width:20%;text-align:center;"><?php _e('Score','leagueengine');?></th>
<th style="width:30%;text-align:center;"><?php _e('Away','leagueengine');?></th>
</tr>
<tr class="date">
<td><input type="text" class="leagueengine_datepicker" name="match_date" value="<?php echo date(leagueengine_fetch_settings('date_format_php'),strtotime($match->match_date));?>"></td>
<td colspan="3"></td>
</tr>
<input type="hidden" name="tournament_match_id" value="<?php echo $match->id;?>">
<input type="hidden" name="home_team_id" value="<?php echo $match->home_team_id;?>">
<input type="hidden" name="away_team_id" value="<?php echo $match->away_team_id;?>">
<input type="hidden" name="date_alt" class="leagueengine_datepicker_alt" value="<?php echo $match->match_date;?>">
<input type="hidden" name="time_alt" class="leagueengine_timepicker_alt" value="<?php echo $match->match_time;?>">
<tr>
<td><input type="text" class="leagueengine_timepicker" name="match_time" value="<?php echo date(leagueengine_fetch_settings('time_format_php'),strtotime($match->match_time));?>"></td>
<td style="text-align:center;"><?php echo leagueengine_fetch_data_from_id($match->home_team_id,'data_value') ;?></td>
<td style="text-align:center;">
<input style="width:48%;text-align:center;" type="text" name="home_team_score" value="<?php echo $match->home_team_score;?>">
<input style="width:48%;text-align:center;" type="text" name="away_team_score" value="<?php echo $match->away_team_score;?>">
</td>
<td style="text-align:center;"><?php echo leagueengine_fetch_data_from_id($match->away_team_id,'data_value') ;?></td>
</tr>
<?php if($tournament_row->pts_bonus == 'on') { ?>
<tr>
<td></td>
<td style="text-align:center;"><?php _e('Bonus Points','leagueengine');?></td>
<td style="text-align:center;">
<input style="width:48%;text-align:center;" type="text" name="home_team_bonus" value="<?php echo $match->home_team_bonus;?>">
<input style="width:48%;text-align:center;" type="text" name="away_team_bonus" value="<?php echo $match->away_team_bonus;?>">
</td>
<td style="text-align:center;"><?php _e('Bonus Points','leagueengine');?></td>
</tr>
<?php } ?>
</table>
<input style="margin-top:20px;" type="submit" name="save_tournament_match" class="button-primary" value="<?php _e('Save','leagueengine');?>" />
<input style="margin:20px 0 0 10px;" type="submit" name="tournament_match_swap" class="button" value="<?php _e('Swap Teams','leagueengine');?>" style="float:right;margin-right:10px;" />
</form>
</div>
<?php
$table = $wpdb->prefix . 'leagueengine_player_careers';
$homeplayers = $wpdb->get_results("SELECT * FROM $table WHERE tournament_id = '$tournament_id' AND team_id = '$home_team_id'");
$awayplayers = $wpdb->get_results("SELECT * FROM $table WHERE tournament_id = '$tournament_id' AND team_id = '$away_team_id'");
if($homeplayers or $awayplayers && $league_type != 'players') {
?>
<div id="lineups">
<?php echo leagueengine_tournament_match_lineups($tournament_id,$match_id);?>
</div>
<?php } ?>
<?php if(leagueengine_data_exists('event')) { ?>
<div id="events">
<?php echo leagueengine_tournament_match_events($tournament_id,$match_id);?>
</div>
<?php } ?>
<?php if(leagueengine_statistics_exists('tournament_match')) { ?>
<div id="statistics">
<?php echo leagueengine_fetch_statistics('tournament_match',NULL,NULL,$tournament_id,$match_id);?>
</div>
<?php } ?>
<?php if(leagueengine_h2h_history($match->match_date,$home_team_id,$away_team_id)) { ?>
<div id="history">
<?php echo leagueengine_fetch_h2h_history($match->match_date,$home_team_id,$away_team_id);?>
</div>
<?php } ?>
<div id="report">
<form action="" method="post">
<div class="setting">
<table class="form">
<tr><th><?php _e('Match Report','leagueengine');?></th></tr>
</table>
<?php wp_editor( stripslashes_deep($match->report), 'match_report', array( 'media_buttons' => true, 'tinymce' => true, 'quicktags' => true, 'textarea_rows' => 20 )); ?>
</div>
<input style="margin-top:20px;" type="submit" name="save_tournament_match_report" class="button-primary" value="<?php _e('Save','leagueengine'); ?>">
</form>
</div>
</div>
</div>
</div>
</div>

displaying csv data in four columns in php

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;
?>

Categories