Log in

View Full Version : Increment counter with conditions



glucarelli
03-13-2011, 10:25 PM
Hi,

I have this php code to insert values in a database :

$eid = $_GET['parameter1'];
$file= $_GET['parameter2'];

$db_conn = mysql_connect('xxxxxx', 'xxxxxx', 'xxxxxx') or die ("Database CONNECT Error (line 11)");

$insert_st = "INSERT INTO opened values ('".$id."','".$eid."', '".$file."', now())";
mysql_db_query('xxxxxx', $insert_st) or die ("Database failed to insert");

I would like to insert ( have to create it first ) a new row (named count) created or updated with this conditions :


First case :
If $eid = X AND $file= A , and there is no record matching this criteria, table count begins at 1


Second case :
If $eid = X AND $file= A ,and there is already a record matching this criteria, table count increment by 1

How can i do that :confused:

Any advice would be helpfull ;)

Regards

james438
04-21-2011, 02:24 AM
when inserting a value into the database it should look something like

INSERT INTO table ('ID','col1','col2') VALUES ('$ID','$value1','$value2');

Get the ID from the address and see if it exists in the database:


$ID=$_GET['ID'];
if (is_numeric($ID)){
$get_addresses = "SELECT ID FROM table WHERE ID = $ID";
$get_addresses_res = mysql_query($get_addresses);
$add_info = mysql_fetch_array($get_addresses_res);
$ID = $add_info['ID'];
}

I do not use the auto_increment feature of MySQL and created my own version, which I prefer.

The following will generate the number for your row ID which will fill in gaps in your table if they exist. This assumes that the auto_increment is not turned on for your table. The row starts at row 0. I added some notation for clarification.


#############
if (is_null($ID)){$new='yes';
$ID2=0;$ID1=0;
$get_list1 = "SELECT ID FROM table ORDER BY ID ASC";
$get_list_res1 = mysql_query($get_list1) or die(mysql_error());
while ($recs1 = mysql_fetch_array($get_list_res1)) {$ID2++;
$IDa = $recs1['ID'];
if ($ID1===0 and $ID2=="1" and $IDa>0) {$ID1=0;break;} ##if the first gap is at row 0 then set the value at 0 and break.
if (($IDa-$ID1)>1) {$ID1=$ID1+1;break;} ##If a gap is detected then break and set the value as the first gap available.
$ID1=$IDa;
} if (is_null($ID1)) {$ID1=0;} ##if there are no rows in the table set the value of the first row as 1.
}if ($ID1==$IDa)$ID1++;
#############
The following will create your query:

If ($new ='yes') $insert_st="INSERT INTO table ('ID','col1','col2') VALUES ('$ID','$value1','$value2')"
else $insert_st=UPDATE table SET ID='$ID', col1='$value1', col2='$value2' WHERE ID='$ID';