Page 1 of 1

php code causes a double entry in mySQL

Posted: Thu Oct 16, 2008 6:25 pm
by kevin216
this code monitors port 8080 and writes the input in to a MySQL table.

But it keeps adding 2 rows instead of 1.the first one is filled with data and the other is blank .I can't seem to stop it adding this blank row
any help would be great.I'm very new to php
.
thanks.

Code: Select all

 
<?php
// Set time limit to indefinite execution
set_time_limit (0);
 
// Set the ip and port we will listen on
$address = '127.0.0.1';
$port = 8080;
$username = "root";
$password = "";
$hostname = "localhost";
$i=0;
// Create a TCP Stream socket
 
 
 
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
// Bind the socket to an address/port
socket_bind($sock, $address, $port) or die('Could not bind to address');
// Start listening for connections
socket_listen($sock);
$dbh = mysql_connect($hostname, $username, $password) 
    or die("Unable to connect to mysql");
print "connected to mysql<br>";
$selected = mysql_select_db("first_test",$dbh) 
    or die("Could not select first_test");
 
 
/* Accept incoming requests and handle them as child processes */
$client = socket_accept($sock);
//$input = socket_read($client, 1024);
// Read the input from the client &#8211; 1024 bytes
 //$name[1-5] = 'r';
  while(1)
{
 
 
 
$input = socket_read($client, 1024);
 
 
 
if ($input==null){
 
}
else{
$i=$i+1;
 
 
$longa=substr($input,0,20);
$lat=substr($input,20,40);
print ($input);
 
if ($longa=="")
{}
else{
if (mysql_query("insert into gps values($i,'$longa','$lat')")) {
  print "successfully inserted record";
   $input2 = $input;
}
else {
      print "Failed to insert record";
}
 
}
 
}}
mysql_close($dbh);
socket_close($client);
 
 
socket_close($sock);
 
?> 
 
 
thanks

Re: php code causes a double entry in mySQL

Posted: Thu Oct 16, 2008 7:33 pm
by SBro
The insert is contained within a while(1) {} loop which is why it is inserting more than one record. You might want to try formatting your code a little better as well (correct indentation, spacing etc. as it will make it easier to read and debug :) )