Page 1 of 1

replace when submit

Posted: Mon Mar 26, 2007 11:14 am
by Annaccond
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I need to put on my site form which would allow add some content to database. It have to be like simple guestbook but I want to it not add new records to database but replace those which already exist. In other words: I want to in database could be only 1 record (last submitted).

Those are my codes:

SUBMIT FORM:

Code: Select all

<form id="form1" name="form1" method="post" action="postfile.php"> 
<input name="myTEXT" type="text" id="myTEXT" size="40" /> 
<input type="submit" name="Submit" value="Submit" /></td> 
</form>
DATABASE:

Code: Select all

CREATE TABLE `test_db` ( 
`myTEXT` varchar(65) NOT NULL default '', 
PRIMARY KEY (`myTEXT`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;
POST FILE:

Code: Select all

$host="bla bla bla"; 
$username="bla bla bla"; 
$password="bla bla bla"; 
$db_name="bla bla bla"; 
$tbl_name="test_db"; 

mysql_connect("$host", "$username", "$password")or die("cannot connect server "); 
mysql_select_db("$db_name")or die("cannot select DB"); 

$sql="INSERT INTO $tbl_name(myTEXT)VALUES('$myTEXT')"; 
$result=mysql_query($sql); 

if($result){ 
echo "Successful"; 
} 

else { 
echo "ERROR"; 
} 

mysql_close();
It working but adding another records to database. I tried replace INSERT by UPDATE but I'm getting error. Could someone help me create working code, please?


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Mon Mar 26, 2007 11:33 am
by blackbeard
If I understand your problem correctly, use REPLACE instead of INSERT:

Code: Select all

$myTEXT = mysql_real_escape_string($_POST['myTEXT']);

$sql="REPLACE INTO $tbl_name (myTEXT) VALUES ('$myTEXT')";

Posted: Mon Mar 26, 2007 11:59 am
by Annaccond
Unfortunately it still adding another records to database without replacing those old.

It's like:

SUBMIT ---> "1st message"
SUMBIT ---> "1st message", "2nd message"
SUBMIT ----> "1st message", "2nd message", "3rd message" etc

and I need to it work like this:

SUBMIT ---> "1st message"
SUMBIT ---> "2nd message" (1st is deleting and replaced by new submitted)
SUBMIT ----> "3rd message" (2nd is deleting and replaced by new) etc

Posted: Tue Mar 27, 2007 1:16 am
by hoangvu.che
You want to have only one record in the table.

Why dont you run a DELETE query before the INSERT query.

Posted: Tue Mar 27, 2007 6:17 pm
by Annaccond
I did and that solve the problem :)