Tribalcomm
Tribalcomm

Reputation: 27

Script working with mysql and php into a textarea and back

I am trying to write a custom script that will keep a list of strings in a textarea. Each line of the textarea will be a row from a table.

The problem I have is how to work the script to allow for adding, updating, or deleting rows based on a submit.

So, for instance, I currently have 3 rows in the database: john sue mark

I want to be able to delete sue and add richard and it will delete the row with sue and insert a row for richard.

My code so far is as follows:

To query the db and list it in the textarea: $basearray = mysql_query("SELECT name FROM mytable ORDER BY name");

<textarea name="names" cols=6 rows=12>');
<?php
   foreach($basearray as $base){
      echo $base->name."\n";
   }
?>
</textarea>

After the submit, I have:

<?php
$namelist = $_REQUEST[names];
$newarray = explode("\n", $namelist);

foreach($newarray as $name) {
   if (!in_array($name, $basearray)) {
      mysql_query(DELETE FROM mytable WHERE word='$name'");
   } elseif (in_array($name, $basearray)) {
      ;
   } else {
      mysql_query("INSERT INTO mytable (name) VALUES ("$name")");
   }
} 

?>

Please tell me what I am doing wrong. I am not getting any functions to work when I edit the contents of the textarea.

Thanks!

Upvotes: 0

Views: 231

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157892

The answer is simple. Don't do it using textarea. That's what you're doing wrong.

List your strings in HTML table, with "Edit" and "Delete" buttons. Edit your rows by one and you'll never have any problem.

As for your approach to treat a database as a plain text file, be consistent and think of it as a plain text file. So, it must be emptied before writing.

Edit:
Or - even much,much better - get rid of the database and use a txt file instead.

So, your code become as simple, as

<textarea name="names" cols=6 rows=12>');
<?php readfile('base.txt') ?>
</textarea>

and form handler is

<?php file_put_contents("data.txt",$_REQUEST['names']); ?>

Upvotes: 1

Related Questions