Hello, I'm trying to update a database using php. I have to add patient id in the format of 'p99' and if it reaches the highest number it should go to the next alphabet like 'q01'. I have this piece of code but it doesn't seem too be doing the job. What would I have to fix?

if ($_REQUEST["submitter"]=="Save")
  {
   if ($_REQUEST["patientid"]=="(System Specified)")
   {
    $queryres=$mydb->query("Select * from patient where PatientID=patientid");
    if ($queryres->countReturnedRows()==0)
     $patientid=111;
    else
    {
     $queryres=$mydb->query("Select Max(patientid) as mx from patient");
     $resultrow=$queryres->fetchRow();
     $patientid=$resultrow['mx']+1;
    }
    $mydb->execute("Insert Into Patient ".
           "(PatientId, patientname, address,".
           "gender, bloodtype, spam,".
           "organs)".
           " Values (%i,%s,%s,%s,%i,%b,%b)",
           $patientid,
           $_REQUEST["patientname"],
           $_REQUEST["address"],
           $_REQUEST["gender"],
           $_REQUEST["bloodtype"],
           $_REQUEST["spam"],
           $_REQUEST["organs"]);
    $onloaddo="alert('Saved new patient ".$patientid."');";
    $patientid="";
   }
  }  {

I am not sure whether I got exactly what you want but I can suggest you use a function that will return the ID formed as a string. Something like:

function getCustomID($id) {

    // check if ID is within the limits (you can go from a01 to z99 only)
    if($id < 1 || $id > 2574) {

        die("Value $id is out of limits!");
    }

    // get the alpha phart (the letter)
    // ascii code for the character a = 97
    $charIndex = ceil($id / 99) - 1 + 97;
    $alphaPart = chr($charIndex);

    // get the temporary number between 1 and 99
    $tempNum = $id % 99 == 0 ? 99 : $id % 99;

    // get the numeric part (just temporary number padded with 0)
    $numericPart = str_pad($tempNum, 2, '0', STR_PAD_LEFT);

    // return the string that represents the ID
    return $alphaPart . $numericPart;
}

And here is a little test of what the function does:

// test the function with some test data
$testArray = array(1, 2, 3, 99, 100, 101, 102, 197, 198, 199, 200, 205, 2088, 2574);
foreach($testArray as $patientid) {

    echo "<pre>$patientid: " . getCustomID($patientid) . "</pre><br>";
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.