Jump to content

Prepend letters to an autoincrementing field in mysql


mrjonnytou

Recommended Posts

I am guessing that you want to store this value in the database?  The way I would do it (there may be better ways) is to have 2 fields, the first ID field is used to generate the autonumber (type = integer).  Then the second field is used to create the new ID (type = varchar).  Have a look at the following example:

 

testpage.php

<?php

$dbHost = "localhost"; 
$dbUser = "blah"; 
$dbPass = "blah"; 
$dbname = "blah"; 

$db = mysql_connect($dbHost,$dbUser,$dbPass); 
mysql_select_db($dbname,$db);                

if(isset($_POST['submit'])) {
$urname = $_POST['urname'];
$sql = mysql_query("INSERT INTO tbltest (IDnum, IDmain, urname) VALUES ('', '0', '$urname')");
$lastid = mysql_insert_id();
$IDmain = 'abc_'.$lastid;
$sql2 = "UPDATE tbltest SET IDmain='$IDmain' WHERE IDnum = '$lastid";
$result = mysql_query($sql2);
}

echo '<form name="test" action="testpage.php" method="post">
<input type="text" name="urname" />
<input type="submit" name="submit" value="submit" />
</form>';

?>

 

Hope this helps

mrjonnytou  - To be clear, if the field is an actual "Auto Increment" field, you cannot prepend/append/modify it as the record is added, because the contents of that field are handled by the database ... it has to check what the last value was, and insert the next available number.

 

However, a solution like john-formby suggested will work, though you're adding a record, checking the record, and updating the record for every time you want to enter data.

 

You might want to evaluate exactly why you need to prepend data, and see if there's a workaround from there, because there is definitely a more effecient way to solve your problem, I'm sure.

 

Perhaps you could explain your expected end result, or what the exact problem is you're trying to solve, and we could help you a bit better.

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.