KrisGeor
KrisGeor

Reputation: 53

PHP: How to check if form data is the same as in a text file?

I have a .text file in which I store data like so:

<tr><td>Val 1</td><td>Val 2</td><td>Val 3</td></tr>
<tr><td>Val 1</td><td>Val 2</td><td>Val 3</td></tr>
<tr><td>Val 1</td><td>Val 2</td><td>Val 3</td></tr>

Every minute or so a new string is added.

I have a form with three inputs, val1, val2, and val3. When the form is submitted it saves the values to the text file like this:

[HTML element] Val 1 [2 HTML elements] val2 [2 HTML elements] val3 [2 HTML elements]

My question is: How do I search in the file if a string exists, and if it does, execute a block of code, and if it doesn't, continue and save the data to the file?

I know I can use a database but I have to do it with a .text file.

Upvotes: 0

Views: 982

Answers (2)

kylethebaker
kylethebaker

Reputation: 58

I think the existing answer satisfies the question, but just to comment on the question itself:

Something that could simplify operations is using a different format for your text file. I presume that you are using markup inside of the file so that you can easily display it as html, but you shouldn't let the way your data is displayed dictate the way your data is stored. If you store your data in a CSV then you're able to easily represent your data table as an array, which makes accessing the values much easier as you have a structured and hierarchical representation in memory rather than a single long string.

Not only does this make dealing with the data easier, but this also allows you to easily change the way your data is displayed without having the change the structure of your data. Currently, if you wanted to display your data using divs instead of tables then you would have to change not only all of the data in the text file itself but also all of the places in your code where you expect to be parsing it. By separating the storage representation and visual representation you're able to make these changes in a single location. Using a CSV also allows for better interoperability of your data across other systems.

You could store your data like such:

Val 1a, Val 2a, Val 3a
Val 1b, Val 2b, Val 3b
Val 1c, Val 2c, Val 3c

And then accessing the existing data and saving new data could be:

<?php

define("DATA_FILE", "data.csv");

/**
 * Retrieves the data from the csv file and returns it in the format:
 * [
 *   [
 *     Val1 => ...,
 *     Val2 => ...,
 *     Val2 => ...,
 *   ],
 *   [
 *     Val1 => ...,
 *     Val2 => ...,
 *     Val2 => ...,
 *   ]
 * ],
 */
function getData() {
  // these will be the key names for the fields in the array
  $fieldNames = ["Val1", "Val2", "Val3"];
  $data = [];
  foreach (file(DATA_FILE) as $row) {
    $csvRow = str_getcsv($row);
    $data[] = array_combine($fieldNames, $csvRow);
  }
  return $data;
}

/**
 * Saves new data to the file. Takes data in the form:
 * [
 *   Val1 => ...,
 *   Val2 => ...,
 *   Val2 => ...,
 * ],
 */
function saveNewData($values) {
  $fp = fopen(DATA_FILE, "a");
  fputcsv($fp, [$values["Val1"], $values["Val2"], $values["Val3"]]);
  fclose($fp);
}

Then to print the data array into a table:

<?php
/**
 * Returns HTML markup for displaying the data in a table. Returns something
 * like:
 *
 * <tr><td>Val1</td><td>Val2</td><td>Val3</td></tr>
 * <tr><td>Val1</td><td>Val2</td><td>Val3</td></tr>
 */
function getTableMarkup($data) {
  $markup = "";
  foreach ($data as $item) {
    $markup .= "<tr>";
    foreach ($item as $field) {
      $markup .= "<td>{$field}</td>";
    }
    $markup .= "</tr>";
  }

  return $markup;
}

Then when you tie it all together for your use case you would have something like:

<?php

// get the submitted form values
$newValues = [
  "Val1" => $_REQUEST["Val1"],
  "Val2" => $_REQUEST["Val2"],
  "Val3" => $_REQUEST["Val3"],
];

// fetch the existing data from the file in a structured array
$data = getData();

// check if the newly submitted values already exist in the data
if (in_array($newValues, $data)) {
  echo "Data already exists...";
} else {
  echo "Data doesn't exist, saving it...";
  saveNewData($newValues);
  $data = getData();
}

// display the table of data
echo "<table>" . getTableMarkup($data) . "</table>";

I realize this might not be a change you're able to make at this point, but I think it's still worth mentioning. Also note that here I am assuming that you are checking if a row of data already exists where the three new values are identical to the three existing values in that row. If you wanted to check if the submitted Val1 is identical to a previously submitted Val2 then you would need to change the in_array call into a function that does the appropriate checking. But since the data is formatted in an array, the check would consist simply of iterating over the existing data and comparing whatever fields you want to the new fields.

Upvotes: 1

SNG
SNG

Reputation: 357

First you have to check the file by reading and string search, if the string is not found then perform action. please refer below example.

<?php

$productFile = file_get_contents('products.txt');
$products = str_word_count($productFile, 1);

$status = 'i love watching tv on my brand new apple mac';

$found = false;
foreach ($products as $product)
{
    if (strpos($status,$product) !== false) {
        $found = true;
        break;
    }
}

if ($found) {
    echo 'the status contains a product';
}
else {
    echo 'The status doesnt contain a product';
}

?>

Upvotes: 1

Related Questions