I have a form, populated by an uploaded CSV, and upon submit it saves to my database staging/temp table. However, it's only saving the first 4 of 7 rows.
The form:
$file = $_FILES["file"]["tmp_name"];
$handle = fopen($file, "r");
$maxPreviewRows = PHP_INT_MAX; // this will be ~2 billion on 32-bit system, or ~9 quintillion on 64-bit system
$hasHeaderRow = true;
echo "<form method='post' action='/form-submit' >";
echo '<table>';
/*WE WILL NEED TO QA CONDITIONS AND HIGHLIGHT IN RED HERE. ALSO NEED BORDER STYLINGS*/
if ($hasHeaderRow) {
$headerRow = fgetcsv($handle);
echo '<thead><tr>';
foreach($headerRow as $value) {
echo "<th>$value</th>";
}
echo '</tr></thead>';
}
echo '<tbody>';
$rowCount = 0;
while ($row = fgetcsv($handle)) {
$colCount = 0;
echo '<tr>';
foreach($row as $value) {
echo "<td><input name='row[".$rowCount."][".$colCount."]' type='text' value='$value' /></td>";
$colCount++;
}
echo '</tr>';
if (++$rowCount > $maxPreviewRows) {
break;
}
}
echo '</tbody></table>';
echo "<input type='submit' name='confirm' value='confirm'>";
echo '</form>';
}
The submission:
foreach ($_POST['row'] as $rowValue)
{
if( is_array($rowValue) && count($rowValue) > 0 )
{
$sqlFull = "INSERT INTO staging VALUES( DEFAULT, ". substr( str_repeat ( '?, ', count($rowValue) ), 0, -2 ) .")";
if( !$stmt = $connect->prepare($sqlFull) )
{
echo "Prepare failed: (" . $connect->errno . ") " . $connect->error;
}
$stmt->bind_param( str_repeat ( 's', count($rowValue) ), ...$rowValue );
$stmt->execute();
}
}
So it's definitely working but for some reason it's stopping on the fourth row every time. I edit the first field of each row each time and when I check my file dashboard I'll see only the first 4 from each submission.
ANy ideas why this is ending on the 4th row?
UPDATE:
Related
I am trying to pull data from a table in PHPmyadmin and convert it to an HTML table based on some customer form input which filters out unneeded rows. The code below does that fine. The issue is that two of my columns need to contain links.
It would be easy enough to use PHP to change the table data into the link using a strtolower() and str_replace() to remove spaces, then concatinating the "www.website.com/" and the ".html". But I'm using a foreach loop to get all of the rows that I need and I don't know how to only alter one value per row.
I have tried using "Broswer Display Transformations" and "Input Transformations" in PHPmyadmin, but that only seems to affect the data in PHPmyadmin and not when I access the data via PHP.
My current code:
//* Code for Table
$query = "SELECT $searchFields FROM `hose_reels` $searchPhrase ORDER BY `model` ASC";
$result = mysqli_query($cxn,$query);
if ($row[$key] != "0") {
echo '<table width="100%" border="1" class="table"><tr>';
$row = $result->fetch_assoc();
foreach ($row AS $key => $value) {
$key = ucwords(str_replace('_', ' ', $key));
echo "<th>" . $key . "</th>";
}
echo "</tr>";
$result2 = mysqli_query($cxn,$query);
while($row = $result2->fetch_assoc()) {
echo "<tr>";
foreach ($row AS $key => $value) {
$row['$key'] = $value;
echo "<td>$row[$key]</td>";
}
echo "</tr>";
}
echo "</table>";
}
else {
echo "<p>No results match your selection. Please broaden your search.</p>";
}
Just add <a> tag in your php code. Below is the code. One more thing you have error in echo "<td>$row[$key]</td>"; line . it prints <td>$row[$key]</td> not the result you are fetching from DB.
echo '<table width="100%" border="1" class="table"><tr>';
$row = $result->fetch_assoc();
$i = 1;
foreach ($row AS $key => $value) {
$key = ucwords(str_replace('_', ' ', $key));
if($i == 1 || $i ==3){
echo "<th><a href='".key ."'" . $key . "</a></th>";
}else{
echo "<th>" . $key . "</th>";
}
$i++;
}
echo "</tr>";
$result2 = mysqli_query($cxn,$query);
$j =1;
while($row = $result2->fetch_assoc()) {
echo "<tr>";
foreach ($row AS $key => $value) {
$row['$key'] = $value;
if($i == 1 || $i ==3){
echo "<td><a href='".$row[$key]."'".$row[$key]."</a></td>";
}else{
echo "<td>$row[$key]</td>";
}
}
echo "</tr>";
}
echo "</table>";
the roblem is where there is the punch commentator
i need when the column has INTER name or OUTER name to format the content of the $cell
with $cell=number_format($cell,2,',','.')
i'm just starting using php so don be too specific thanks
<?php
// printing table rows
$rigapadi = 1 ;
while($row = mysql_fetch_row($result))
{
echo "<tr>";
$rigapadi=$rigapadi+1;
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
if ($rigapadi % 2 == 0) {
# if column name = 'INTER' or 'OUTER' $cell = number_format($cell, 2, ',', '.');
echo "<td align=\"center\">$cell</td>";
} else {
echo "<td bgcolor=\"#E9EEF5\" align=\"center\">$cell</td>";
}
echo "</tr>\n";
}
mysql_free_result($result);
echo "</table>";
echo "<p/>";
?>
The mysql_ are obsoltes. You must not use them. And please indent your code properly when you ask for help.
<?php
$rigapadi = 1;
while($row = mysql_fetch_assoc($result)) {
echo '<tr>';
$rigapadi++;
foreach($row as $name => $cell) {
if($rigapadi % 2 === 0) {
if($name === 'INTER' || $name === 'OUTER') {
echo '<td align="center">' . number_format($cell, 2, ',', '.') . '</td>';
} else {
echo '<td align="center">' . $cell . '</td>';
}
} else {
echo '<td align="center" bgcolor="#E9EEF5">' . $cell . '</td>';
}
}
echo "</tr>\n";
}
mysql_free_result($result);
echo "</table>";
?>
Note that I use fetch_assoc to get the $name.
PS: <p/> does not exists and align and bgcolor and not valids but acceptable if this is a HTML code for an e-mail.
Thanks for directing the link about the mySql API, i think there is a need to change to mySQLi or PDO. I have post the near-complete code below of same case, as my first time, could you please help what's error below, as it doesn't show the results as expected as the code using mysql_... please help. (assuming the select statement is correct please.)
<?php
$Ticker = htmlspecialchars($_GET["Ticker"]);
$StartDate = htmlspecialchars($_GET["StartDate"]);
$EndDate = htmlspecialchars($_GET["EndDate"]);
echo "<td>testing.</td>";
echo "</table>";
$pdo = new PDO('mysql:host=;dbname=, ,);
$statement = $pdo->query("Select Ticker, xxx as 'Last Update',Price, xxx as TTlUndetAmt,
FROM trade
WHERE Ticker = '$Ticker' and DATE(xxx) between '$StartDate' and '$EndDate'
GROUP BY Ticker, date
ORDER BY Ticker ASC, Date(ReleaseDT) DESC");
$row = $statement->fetch(PDO::FETCH_ASSOC);
//echo htmlentities($row['_message']);
echo "<table>";
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $value) {
if ($value === end($row)) {
echo number_format($value);
} else
{
echo $value . ",";
}
}
echo " </td></tr> " . "\n";
$i++;
}
?>
I got the results from select statement from mysql database. I use php to get the required data. I want specify the format only a specific item of each row to be numeric, i.e. (thousand separated). How could I do so? can below code do so?
Current output:
ticker1,2014-09-03 ,1.190,0,37247000
ticker2,2014-09-03 ,1.180,0,23246000
ticker3,2014-09-03 ,1.170,0,19188000
Expected Output:
ticker1,2014-09-03 ,1.190,0,37,247,000
ticker2,2014-09-03 ,1.180,0,23,246,000
ticker3,2014-09-03 ,1.170,0,19,188,000
The code I am using:
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $value) {
echo $value . ",";
if ($value === $row[5]) {
echo number_format($value);
}
}
echo " </td></tr> " . "\n";
$i++;
}
echo "</table>";
I found out that the above code will create duplicate role at the last row [5].
To my limited knowledge, I changed to
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $value) {
if ($value === end($row)) {
echo number_format($value);
} else
{
echo $value . ",";
}
}
echo " </td></tr> " . "\n";
$i++;
}
I would incorporate the key. That way, you can just check for the field name:
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<tr><td>";
foreach ($row as $key => $value) {
echo $value . ",";
if ($key === 'YourFieldName') {
echo number_format($value);
}
}
echo " </td></tr> " . "\n";
$i++;
}
echo "</table>";
The function mysql_fetch_assoc already returns a key/value array, so you don't need anything there. Note though, that mysql_fetch_assoc is part of an old and deprecated API. If you like, have a look at: Choosing a MySQL API.
I would bring in the names, and use a $key=>$val in your foreach as such:
foreach ($row as $key=>$value)
{
echo $value . ",";
if ($key == "theRightColumn") // guessing the column name
{
echo number_format($val);
}
else
{
echo $val;
}
}
You have to change the modification in this line
foreach ($row as $value) {
to
foreach ($row AS $key => $value) {
i got this script. it looks into a file and read all the lines and put it nicely in a table.. what i need to do now is to take all the table data and split it into two tables ..
eg. if their is 100 rows.. then instead of one long list, i will get 50 data in one table and the other 50 in the other table...
enter code here<?php
if(isset ($_GET['type']))
{
$otype = $_GET['type'];
}
else
{
$otype = 'm';
}
$statusFile = "d:\\CLIENTS\\status.txt";
$file_handler = fopen($statusFile, "r");
// read the contents
$contents = fread($file_handler, filesize($statusFile));
// close the file
fclose($file_handler);
if (strcasecmp($otype, "m") == 0)
{
echo $contents;
}
else
{
$lines = explode("\n",$contents);
$frow = explode(",", $lines[0]);
if (strcmp($frow[1],"1") == 0)
{
echo "Update Status: <b>Complete</b>";
//to count total lines in txt file
$statusFile = "d:\\CLIENTS\\status.txt";
$line = count(file($statusFile));
echo "There are".$line."lines in";
}
else
{
echo "Update Status: <b>Incomplete</b>";
}
echo "<table border=\"1\">";
for ($count = 1; $count < sizeof($lines); $count++)
{
$fields = explode(",",$lines[$count]);
$sz = sizeof($fields);
if ($sz > 1)
{
$str = "OK";
echo "<tr>";
echo "<td>" . $fields[0] . "</td>";
echo "<td>" . $fields[1] . "</td>";
//echo "<td>" . $fields[2] . "</td>";
if (strpos($fields[2],'OK') !== false)
{
echo "<td><font color='green'>". $fields[2] ."</font></td>";
//echo "<td style='background-color: #00FF00;'>". $fields[2] ."</td>";
}
else
{
//echo "<td><font color='red'>". $fields[2] ."</font></td>";
echo "<td style='background-color: #FF0000;'>". $fields[2] ."</td>";
}
echo "</tr>";
}
}
echo "</table>";
}
?>
Use a foreach instead of a for and $count to calculate if it is needed to echo a table tag. $count is only incremented when a row was inserted.
<style>
div.container {
width: 100%; /* Change the width to the desired width */
padding: 0;
}
div.container table {
width: 50%; /* Change the width to half of the width of the div */
margin: 0;
float: left;
}
</style>
<?php
if(isset ($_GET['type']))
{
$otype = $_GET['type'];
}
else
{
$otype = 'm';
}
$statusFile = "d:\\CLIENTS\\status.txt";
$file_handler = fopen($statusFile, "r");
// read the contents
$contents = fread($file_handler, filesize($statusFile));
// close the file
fclose($file_handler);
if (strcasecmp($otype, "m") == 0)
{
echo $contents;
}
else
{
$lines = explode("\n",$contents);
$frow = explode(",", $lines[0]);
if (strcmp($frow[1],"1") == 0)
{
echo "Update Status: <b>Complete</b>";
//to count total lines in txt file
$statusFile = "d:\\CLIENTS\\status.txt";
$line = count(file($statusFile));
echo "There are".$line."lines in";
}
else
{
echo "Update Status: <b>Incomplete</b>";
}
echo '<div class="conatiner">';
$count = 0;
foreach ($lines as $currLine)
{
$fields = explode(",",$currLine);
$sz = sizeof($fields);
if ($sz > 1)
{
if ($count == 0) {
echo "<table border=\"1\">";
}
elseif ($count % 50 == 0) {
echo "</table>";
echo "<table border=\"1\">";
}
$str = "OK";
echo "<tr>";
echo "<td>" . $fields[0] . "</td>";
echo "<td>" . $fields[1] . "</td>";
//echo "<td>" . $fields[2] . "</td>";
if (strpos($fields[2],'OK') !== false)
{
echo "<td><font color='green'>". $fields[2] ."</font></td>";
//echo "<td style='background-color: #00FF00;'>". $fields[2] ."</td>";
}
else
{
//echo "<td><font color='red'>". $fields[2] ."</font></td>";
echo "<td style='background-color: #FF0000;'>". $fields[2] ."</td>";
}
echo "</tr>";
$count++;
}
}
echo "</table>";
echo '</div>';
}
i posted a question a while ago and i got my answer but now i kind of want a followup to this problem so i have a table like the one in the picture but i want to add total to each row or in fact a group how can i do that.
This is the php code to create this table how to edit it to add the total.
$sql = mysql_query(
"SELECT s.login AS 'from', r.login AS 'to',COUNT(*) as'message_count'
FROM messages AS m,groups AS s,groups AS r
WHERE m.Group_ID = s.id
AND m.To_Group_ID = r.id
AND m.Simulation_ID = ".$_SESSION['sim_id']."
AND s.kind_of_user NOT IN (3,1)
AND r.kind_of_user NOT IN (3,1)
AND m.Group_ID IN
(SELECT Group_ID FROM simulationgroups
WHERE Simulation_ID = ".$_SESSION['sim_id'].")
AND m.To_Group_ID IN
(SELECT Group_ID FROM simulationgroups
WHERE Simulation_ID = ".$_SESSION['sim_id'].")
GROUP BY m.Group_ID, m.To_Group_ID
ORDER BY s.id DESC"
) or die (mysql_error());
$data = array();
while($row = mysql_fetch_assoc($sql))
{
$data[$row['to']][$row['from']] += $row['message_count'];
}
// Print headers
$columns = array_keys($data);
echo "<table class='msg_dynamics' cellspacing=0
cellpadding=0 border=1px><tr><th><<</th>";
foreach($columns as $_column)
{
echo "<th width='10%'>{$_column}</th>";
}
echo "<th width='10%'>total</th>";
echo "</tr>";
// Print data
foreach($data as $_row_name => $_row_data)
{
// Add the dash (-) for empty cells
$_row_data[$_row_name] = '-';
echo "<tr><td width='10%'>{$_row_name}";
foreach($columns as $_col_name)
{
echo "<td>{$_row_data[$_col_name]}</td>";
}
echo "</td></tr>";
}
echo "<tr><td><b>total</b></td>";
";
You have to implement a total counter like :
// Print data
foreach($data as $_row_name => $_row_data) {
// Add the dash (-) for empty cells
$_row_data[$_row_name] = '-';
$total_row = 0; //initialize
echo "<tr><td width='10%'>{$_row_name}</td>";
foreach($columns as $_col_name) {
echo "<td>{$_row_data[$_col_name]}</td>";
if ($_row_data[$_col_name] != '-') {
$total_row += $_row_data[$_col_name];
$total_col[$_col_name] += $_row_data[$_col_name];
}
}
echo "<td>{$total_row}</td>";
echo "</tr>";
}
echo "<tr><td><b>total</b></td>";
foreach ($total_col as $name => $val) {
echo "<td>$val</td>";
}