I am very new to PHP and am trying to create a basic form. This form has a drop-down list whereby the product is displayed. What I would like for it to do is to display the price, and the city that this product is from.
I have a text file which acts as the data source, and is formatted in this way:
product | price | city
Code:
<?php
$file = 'Product1.txt';
$handle = #fopen($file, 'r');
if ($handle) {
while (!feof($handle)) {
$line = fgets($handle, 4096);
$item = explode('|', $line);
echo '<option value="' . $item[0] . '">' . $item[0]. ' '.$item[1]. ' '.$item[2].'</option>' . "\n";
}
fclose($handle);
}
?>
Overall, when I populate my dropdown list, it works fine, and I've extended the page with the hopes of getting more. However, when I try to echo $item[1] or $item[2] at the end of the page, I get nothing.
Can someone show me what I am missing? I've tried looking for tutorials on this matter but to no avail. Thank you.
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $_POST['D1'];
echo "<br>";
echo $quantity;
?>
You are not getting anything because $item not in scope
put $itemData = array(); at the top after $handle
$file = 'Product1.txt';
$handle = #fopen($file, 'r');
$itemData = array();
if ($handle) {
while (!feof($handle)) {
$itemData[] = explode('|', $line);
$line = fgets($handle, 4096);
$item = explode('|', $line);
echo '<option value="' . $item[0] . '">' . $item[0]. ' '.$item[1]. ' '.$item[2].'</option>' . "\n";
}
fclose($handle);
}
its should work
$data = explode(" | ", file_get_contents("data.txt"));
Related
I have the following attempt at my function, but it's just printing out everything in the contacts.txt file on one line...
function contactsTable(){
$file = fopen("contacts.txt", "r") or die("Unable to open file!");
echo "<tr><th>";
while (!feof($file)){
echo "<tr><th>";
$data = fgets($file);
echo "<tr><td>" . str_replace(',','</td><td>',$data) . '</td></tr>';
}
echo "<tr><th>";
echo '</table>';
fclose($file);
}
contacts.txt example like this;
Row 1 is headers ---> [value1, value2, value3, value4]
Row 2 is data ---> [value5, value6, value7, value8]
Is it possible to change my function so that Row 1 is using <th> tags so they are formatted as headers and the rest of the rows go into <td> tags for table data? I've tried to amend the logic but can't seem to get it.
TIA
Here is your contactsTable() function that prints the first contacts.txt line as table header and some basic HTML formatting for easy reading/debugging.
function contactsTable() {
$file = fopen('contacts.txt', 'r') or die('Unable to open file!');
$row = 0;
echo '<table>' . PHP_EOL;
while (!feof($file)) {
$row++;
$data = fgets($file);
if ($row === 1) {
echo '<tr>' . PHP_EOL;
echo '<th>' . str_replace(',', '</th><th>', $data) . '</th>' . PHP_EOL;
echo '</tr>' . PHP_EOL;
} else {
echo '<tr>' . PHP_EOL;
echo '<td>' . str_replace(',', '</td><td>', $data) . '</td>' . PHP_EOL;
echo '</tr>' . PHP_EOL;
}
}
echo '</table>' . PHP_EOL;
fclose($file);
}
I'm doing a code based on two .txt, one with names and the other with birthdays. I'm reading them and when the day date coincides with the date.txt, the name in the coincident line of the names.txt will be shown, but when I do the comparison, only the last line of the names.txt appears.
That's the code:
<?php
$nome = fopen("nome.txt", "r");
while(!feof($nome)){
$pessoa = fgets($nome);
} fclose($nome);
$current = date("d-m");
$content = fopen("data.txt", "r");
while (!feof($content)){
$linha = fgets($content);
if (strtotime($linha) == strtotime($current)) {
echo $pessoa;
echo '<br>';
}
} fclose($content);
?>
Content of the .txt:
nome.txt:
teste
teste1
teste2
teste3
data.txt:
12-12
18-12
12-12
12-12
You can process line by line from both files at the same time
<?php
$nome = fopen("nome.txt", "r");
$content = fopen("data.txt", "r");
$current = date("d-m");
while(!feof($nome) && !feof($content)){
$pessoa = fgets($nome);
$linha = fgets($content);
if (trim($current) == trim($linha)) {
echo $pessoa;
echo '<br>';
}
}
fclose($content);
fclose($nome);
?>
Or you can read entire file into an array using file function but this may be slower
<?php
$nome = file("nome.txt");
$content = file("data.txt");
$current = date("d-m");
foreach($content as $key => $linha)
if (trim($current) == trim($linha)) {
echo $nome[$key];
echo '<br>';
}
?>
You can open the files and load them in to arrays and use foreach with $key to output them in sync.
$names = explode(PHP_EOL,file_get_contents("none.txt"));
$dates = explode(PHP_EOL,file_get_contents("data.txt"));
Foreach($names as $key => $name){
Echo $name . " " . $dates[$key] . "\n";
}
https://3v4l.org/59ao6
Another way is to combine the two arrays in to one.
This however has a flaw, you can not have two people with the same name.
$days = array_combine($names, $dates);
// Days is now an associate array with name as key and date as birthday.
Foreach($days as $name => $date){
Echo $name . " " . $date . "\n";
}
I am trying to use PHP to interpret a simple CSV log file and print it out as a table.
The file has three columns - a name, followed by two columns with a 1 or a 0 in either.
E.g.
Test,1,0
Test,0,1
Test2,1,0
Test3,1,0
Test3,0,1
Test3,1,0
Test3,0,1
The goal is to sum all identical rows together to give this:
Test,1,1
Test2,1,0
Test3,2,2
And lastly print this as an HTML table.
So far I have a working solution for summing the first two columns but I don't know how to get it to work to include the third. To outline the entire process, I have an initial PHP script at the start of a web page that logs clicks to a CSV file:
<?PHP
if (isset($_GET['s1'])){
$sub1 = urlencode($_GET['s1']);
$fp1 = fopen ('botlog.csv', 'a+' );
fputcsv ( $fp1, array ( $sub1, '1', '0' ), ",", '"' );
fclose ( $fp1 );}
?>
Later I have a second script, loaded in an iFrame with a JS delay, that logs a similar value but to the third column rather than the second:
<?PHP
if (isset($_GET['sub1'])){
$sub2 = urlencode($_GET['sub1']);
$fp2 = fopen ('botlog.csv', 'a+' );
fputcsv ( $fp2, array ( $sub2, '0', '1' ), ",", '"' );
fclose ( $fp2 );}
?>
Then, I have the following to a) aggregate rows for the 2nd column value (haven't figured out how to do the third too) and put into an array, b) dump it all as a table:
<?php
$array = array_map('str_getcsv', file('botlog.csv'));
$inputfile = 'botlog.csv';
$inputHandle = fopen($inputfile, "r");
$sumArray = array();
while (($dataRow = fgetcsv($inputHandle, 1000, ",")) !== FALSE) {
$subid = $dataRow[0];
$extra1 = $dataRow[2];
if (!isset($sumArray[$subid])) {
$sumArray[$subid] = 0;
}
$sumArray[$subid] += $extra1;
}
var_dump($sumArray); //test sum works
function build_table($sumArray){
// start table
$html = '<table>';
// header row
$html .= '<tr>';
$header=array("SUBID"=>"1","Initial Clicks"=>"2","Secondary Clicks"=>"3", "Percentage"=>"4");
foreach($header as $key=>$value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $sumArray as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}
echo build_table($array);
?>
The initial code works in that it makes an array with the column 2 values summed. Woot! However, I then try to use the HTML table print out on this sumArray, but it just displays the original content (i.e. not that generated from the while function.
So, goals:
Modify initial code block to create a $sumArray that merges all identical column 1 rows but adds their column 2 and 3 values.
Print this out in a nifty table with a 4th spare column.
Help much appreciated!
EDIT: This is the final working code I used:
<?php
if (file_exists('botlog.csv')) {
$array = array_map('str_getcsv', file('botlog.csv'));
$inputfile = 'botlog.csv';
$inputHandle = fopen($inputfile, "r");
$sumArray = array();
while (($dataRow = fgetcsv($inputHandle, 1000, ",")) !== FALSE) {
$subid = $dataRow[0];
if (!isset($sumArray[$subid])) {
$sumArray[$subid] = array_fill(0, count($dataRow)-1, 0);
}
for ($i = 1; $i < count($dataRow); $i++) {
$sumArray[$subid][$i-1] += $dataRow[$i];
}}
arsort($sumArray);
$table = $sumArray;
echo '<table>';
echo "<thead><td><span>Subid</span></td><td><span>Initial Clicks</span></td><td><span>Secondary Clicks</span></td><td><span>Percentage</span></td></thead>";
foreach ($table as $subids => $values)
{
echo "<tr><td>".$subids."\n";
echo "<td>" . $values['0'] . "</td>";
echo "<td>" . $values['1'] . "</td>";
echo "<td>Final column contents</td>";
}
echo "</table>";
}
else{ echo "Botlog.csv file was not found in current directory";}
?>
Make $sumArray a 2-dimensional array. The key of the first dimension is the first column of the CSV, and the second dimension is the sums of the remaining columns.
while (($dataRow = fgetcsv($inputHandle, 1000, ",")) !== FALSE) {
$subid = $dataRow[0];
if (!isset($sumArray[$subid])) {
$sumArray[$subid] = array_fill(0, count($dataRow)-1, 0);
}
for ($i = 1; $i < count($dataRow); $i++) {
$sumArray[$subid][$i-1] += $dataRow[$i];
}
Below is a php file used within my e-commerce website (prototype) to write the item(s) selected by a customer and storing their choices in a flat file database. The logic works fine although the echo "Order Submitted!; is printed for every item selected e.g. if 4 items are selected this line is printed 4 times, I only require it to be printed once. Any idea how this could be accomplished?
<body>
<table>
<?php
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
} else {
echo "<h1>Transaction Completed!</h1>";
}
date_default_timezone_set('Europe/London');
$now = date(' d/m/y H:i:s ');
$visitor = $_POST['visitor'];
foreach ($_POST as $varname => $varvalue) {
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname) {
$myFile = "purchases.txt";
$fh = fopen($myFile, 'a') or die("ERROR: Failed to open purchases file!\n");
$content = $now . "|" . $visitor . "|" . $partno . "|" . $name . "|" . $price . "\n";
if (!(fwrite($fh, $content))) {
echo "<p>ERROR: Cannot write to file($myFile)\n</p>";
exit;
} else {
echo "<p>Order Submitted!</p>";
fclose($fh);
}
}
}
}
?>
</table>
<input type="button" onClick="parent.location='home.php'" value="Return Home">
<input type="button" onClick="parent.location='items.php'" value="New Purchase">
If 2 items are selected the output is:
Transaction Completed
Order Submitted!
Order Submitted!
Keep track of if there's an error and move the else outside the loop.
$error=false;
foreach ($_POST as $varname => $varvalue) {
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname) {
$myFile = "purchases.txt";
$fh = fopen($myFile, 'a') or die("ERROR: Failed to open purchases file!\n");
$content = $now . "|" . $visitor . "|" . $partno . "|" . $name . "|" . $price . "\n";
if (!(fwrite($fh, $content))) {
echo "<p>ERROR: Cannot write to file($myFile)\n</p>";
$error=true;
exit;
}
}
}
}
if(!$error) {
echo "<p>Order Submitted!</p>";
fclose($fh);
}
Although, the way you have it written, you don't even need a conditional surrounding "Order submitted" because it will never execute if there's an error. (Due to the exit.)
Also you can move $myfile out of the loop if it doesn't change.
Second version:
$myFile = "purchases.txt";
foreach ($_POST as $varname => $varvalue) {
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname) {
$fh = fopen($myFile, 'a') or die("ERROR: Failed to open purchases file!\n");
$content = $now . "|" . $visitor . "|" . $partno . "|" . $name . "|" . $price . "\n";
if (!(fwrite($fh, $content))) {
echo "<p>ERROR: Cannot write to file($myFile)\n</p>";
exit;
}
}
}
}
echo "<p>Order Submitted!</p>";
fclose($fh);
before foreach loop:
$printed=false;
then instead of
else {
echo "<p>Order Submitted!</p>";
fclose($fh);
}
use
else {
if(!$printed)
{
echo "<p>Order Submitted!</p>";
$printed=true;
}
fclose($fh);
}
You should remove the echo from the else branch and put it right after the first foreach closing bracket
You can use a counter and see if more the one was submitted
like:
$count=0;
foreach ($_POST as $varname => $varvalue) {
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname) {
$myFile = "purchases.txt";
$fh = fopen($myFile, 'a') or die("ERROR: Failed to open purchases file!\n");
$content = $now . "|" . $visitor . "|" . $partno . "|" . $name . "|" . $price . "\n";
if (!(fwrite($fh, $content))) {
echo "<p>ERROR: Cannot write to file($myFile)\n</p>";
exit;
} else {
$count++;
fclose($fh);
}
}
}
}
if ($count>0)
echo "<p>Order Submitted! $count Times</p>";
I use php in order to save all informations concerning my user (where do they navigated and at which time).
So I use the following code for saving informations:
<?php
function iif($condition, $true, $false ) {
return ($condition ? $true : $false);
}
$ipaddress = $_SESSION['login'];
$page = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['PHP_SELF']}";
$page .= iif(!empty($_SERVER['QUERY_STRING']), "?{$_SERVER['QUERY_STRING']}", "");
$referrer = $monUrl = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$datetime = mktime();
$useragent = $_SERVER['HTTP_USER_AGENT'];
$remotehost = #getHostByAddr($ipaddress);
// Create log line
$logline = $ipaddress . '|' . $referrer . '|' . $datetime . '|' . $useragent . '|' . $remotehost . '|' . $page . "\n";
// Write to log file:
$logfile = 'logfile.txt';
$path='log/'.$_SESSION['login'].'/'.$logfile;
if(!file_exists($path)) {
mkdir('log');
mkdir('log/'.$_SESSION['login']);
$f = fopen('log/'.$_SESSION['login'].'/'.$logfile, "x+");
// fermeture
fclose($f);
}
// Open the log file in "Append" mode
if (!$handle = fopen($path, 'a+')) {
die("Failed to open log file");
}
// Write $logline to our logfile.
if (fwrite($handle, $logline) === FALSE) {
die("Failed to write to log file");
}
fclose($handle);
?>
And I use the following code below to display it:
<?php
$path= 'log/'.$data['login'].'/logfile.txt';
$logfile = $path;
if (file_exists($logfile)) {
$handle = fopen($logfile, "r");
$log = fread($handle, filesize($logfile));
fclose($handle);
} else {
die ("Le fichier de Log n'existe pas!");
}
// Seperate each logline
$log = explode("\n", trim($log));
//After that it may be useful to get each part of each logline in a separate variable. This can be done //by looping through each logline, and using explode again:
// Seperate each part in each logline
for ($i = 0; $i < count($log); $i++) {
$log[$i] = trim($log[$i]);
$log[$i] = explode('|', $log[$i]);
}
// Show a table of the logfile
echo '<table id="box-table-a">';
echo '<th scope="col">Agent</th>';
echo '<th scope="col">Referrer</th>';
echo '<th scope="col">Date</th>';
echo '<th scope="col">Useragent</th>';
echo '<th scope="col">Remote Host</th>';
foreach ($log as $logline) {
echo '<tr>';
echo '<td><a href="index.php?p=voir_fiche_employee&id='.$_GET['id'].'"/>' . $logline['0'] . '</a></td>';
echo '<td><a href="'.urldecode($logline['1']).'"/>'. urldecode($logline['1']) . '</a></td>';
echo '<td>' . date('d-m-Y h:i:s', $logline['2']) . '</td>';
echo '<td>' . $logline['3'] . '</td>';
echo '<td>' . $logline['4'] . '</td>';
echo '</tr>';
}
echo '</table>';
?>
The trouble I met is that I really do not know how to sort informations from this file.
In fact on the top of the page I have a form in order to choose between the dates. I wsould like to display all informations from this logfile between those dates but I really do not know how to do.
At the beginning I was planning to save all in the databse, but somebody told me that it would have been too much for the databse, so I decided to save all in a txt on the server.
Does anyone know if it is possible to sort informations from txt file?
By default I would like to display informations of the logfile for the date of the day, and If I want I can choose an other dates or an interval of dates.
If possible to store data into a database. It is easy to sort in database. Reading data into a text file is more time consuming and difficult to sort.