I have a mysql database with about 800 columns at the moment and add to it every so often.
How do I add a new field with a random string of 4 letters and numbers eg : 4h3k
I do not want duplicates to happen either.
Thanks chaps!
EDIT
OH MA GAD NO I MEAN ROWS NOT COLUMNS.
800 ROWS!
As the comments already show. Why in the world would you want 800 columns? Seems like a mayor flaw in your database structure. Perhaps you can explain what you want to store so we can help you to setup a proper structure. 800 (random!) columns can never be what you want.
If you do plan to keep this structure, you could use SHOW COLUMNS FROM mydb.mytable WHERE FIELD='newcolname'
to see if it already exists.
But I highly recomment to reconsider your database model. How are you even selecting things from it since its random columns? You always use select * and then loop trough all cols?
this maybe can help you .
// first u generate string with numbers and letters with length 4
function genRandomString() {
$length = 4;
$characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
echo genRandomString(); // will echo one radom string like 4h8l
// second check if the random string exist in table then use new generated string
$new_random_string = genRandomString() ;
$strings = mysql_query("SELECT `string` FROM `table`");
while ($string = mysql_fetch_row($strings)) {
if ($new_random_string == $string[0])
echo genRandomString() ;
}
mysql_query("INSERT INTO `table` (`string`) VALUES ('".$new_random_string."')");