Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php run once and insert twice in mysql database

Tags:

php

mysql

insert

I've got a simple code below. After it's run once, it inserts results twice into the mysql database.

if it run twice or request twice base on 1 refresh on the page, why the output is just 1 result?

I have been googling for the whole day and struggling to resolve this issue. However, I failed to figure out what is wrong with this code. The code runs perfectly on localhost, but after it's moved to the server, the problem pops up. Has anyone faced something like this before? How can this problem be resolved?

FULL CODE:

<?php
$db=mysql_connect('localhost','zzzzzzz','xxxxxx') or die('Unable to connect.'.mysql_error());
mysql_select_db('test',$db) or die(mysql_error($db));

$sql="INSERT INTO test_table(value,insert_time) VALUES ('testing','".time()."')";
$result=mysql_query($sql);
echo "result=".$result;

$select="select * from test_table";
$rs=mysql_query($select);
while($row=mysql_fetch_array($rs)){
echo $row["test_id"]." -- ".$row["value"]." -- ".$row["insert_time"]."<br />";
}
?>

RESULT:
result=1
1 -- testing -- 1298185509

BUT IN DATABASE:
test_id , value , insert_time
1 , testing , 1298185509
2 , testing , 1298185511

like image 715
nicng Avatar asked Feb 20 '11 07:02

nicng


1 Answers

Do you see this

$result = $db->query($query);

And the next line:

if ($db->query($query) === TRUE) {

This means that you run your query twice. Remove one of the $db->query, e.g.:

$result = $db->query($query);
if ($result === TRUE) {    /* do stuff */
like image 112
amer hamdan Avatar answered Oct 06 '22 00:10

amer hamdan