autoincrement alphanumeric in phpmyadmin mysqlserver - php

i want to autoincrement the alphanumeric characters
Ex:amp001,amp002,amp003
Can anyone plz help me in solving this problem.
i should get column like
id
abc001
abc002
abc003
abc004
..
..
..

You can't auto increment alphanumeric values. Just Change the field type to numeric and set auto increment to that field. Concate your string value before the ID, while fetching the value. Eg: <?php echo "abc".$row['id']; ?>

If you really want this, use php's uniqid function.

Look this example
//connect to you database
//$count = mysql_query("select count(*) from table_name");
$id = "abc";
if (strlen($count+1) < 4)
{
$count++;
for($i=0;$i<(3 - strlen($count));$i++)
{
$id .='0';
}
$id .= $count;
}

Related

Generating CDKey works, checking if exists doesnt

I have a problem with my code.
The first one works, it will generate a cdkey and enter it to the mysql db.
<?
function createRandomKey($amount)
{
$keyset = "abcdefghijklmABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$randkey = "";
for ($i=0; $i<$amount; $i++)
$randkey .= substr($keyset, rand(0, strlen($keyset)-1), 1);
return $randkey;
}
if($_POST['post_true'] == "true")
{
$randomkey = createRandomKey(20);
query(" INSERT INTO cdkeys (`cdkey`,`used`,`user_id`) VALUES (' ".escapeadmin($randomkey)."', '".escapeadmin(0)."', '".escapeadmin(0)." ') ");
echo "<b>Generated Key:</b> ";
echo $randomkey;
}
?>
it will rand different numbers and characters, a-z0-9, the cdkey length is 20 chars.
the second code is the one for checking if the cdkey exists in the databse.
<?
// FETCH POSTED CDKEY
$postedkey = $_POST['cdkey'];
$sql_check_cdkey = query("SELECT * FROM cdkeys WHERE cdkey = '".escape($postedkey)."' ");
$qry_check_cdkey = mysql_fetch_array($sql_check_cdkey);
if(mysql_num_rows($sql_check_cdkey) == "0") { red("Wrong CD Key Entered"); echo $_POST['cdkey']; }
else
{
echo "exists, magic time";
}
?>
now the problem is, that whenever i enter the key , lets say:
736KhYDmZhm1G1P72Ja5HIUg4VcBd9
that is in the databse (i checked, and the generator even echo the key for me)
the key cannot be find. i always get cd key don't exists message.
the key is there, but it's just not finding it.
i tried to change the key from the numbers and characters to "testkey123" and when i tried to search, it worked this time.
it seems like it cant find it as random characters.
what am i missing? i really need to fix it.
thank you
Your test string '736KhYDmZhm1G1P72Ja5HIUg4VcBd9' is 30 characters long - but you say that "cdkey length is 20 chars". You are probably truncating the string when you store it.
Change the size of the column that stores the string:
ALTER TABLE tablename CHANGE cdkey cdkey varchar(100)

mysql count occurrences of special character in a field

I am wanting to count all occurrences of the # symbol in a field and originally i thought LIKE '%#%' would be the way to go, but if the character appears in the field more than once it only counts it as one.
What other method are there that i could use that would count every occurrence?
Thanks.
EDIT
For anyone needing it, this is what i ended up using that works.
$count = 0;
$sql = mysql_query("SELECT LENGTH(field_name) - LENGTH(REPLACE(field_name,'#','')) AS 'occurs' FROM table_name WHERE field_name LIKE '%#%'");
while ($data = mysql_fetch_assoc($sql)) {
$count += $data['occurs'];
}
echo $count;
select length('aa:bb:cc:dd')-length(replace('aa:bb:cc:dd',':',''));
source: http://lists.mysql.com/mysql/215049
You could make this even simpler by using the ``substr_count function in php. see below.
$message = $row['themessage'];
echo substr_count($message, '#');
what this will return is the number of times # has occurred in your "themessage" field in your database.

How can I generate a random and unique id based on the current table row using PHP and MySQL?

I have a table that has an auto-increment "id". I have another column in the same table that has a "key", which I want to be based on the auto-increment "id". This will ensure that there is never a duplicate "key". I want to preferably have a 6 character unique id generator. I found this online, but I am open to other suggestions.
echo $result['id'] . '_' . uniqid('', true);
this will produce something like 1_513c5858c04967.71142475, the prefix ID_ will be always unique based on the database ofcourse
isnt it unique enough?
ahh you want 6 characters, what about:
function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')
{
$str = '';
$count = strlen($charset);
while ($length--) {
$str .= $charset[mt_rand(0, $count-1)];
}
return $str;
}
$key = $result['id'] . '_' . randString(6); //this is unique, cause even you get at a chance of a million that you will get 2 same randString(6); you will have always unique prefix ID_ so you will have 1_G7owOq and 2_G7owOq
//the code below is just an example of how to loop column for unique key and u dont need it :P just maybe someone else needs it.
while(mysqli_num_rows(mysqli_query($con, "SELECT id FROM table WHERE key = '".mysqli_real_escape_string($con, $key)."'")) > 0) {
$key = $result['id'] . '_' . randString(6);
}
Then there is the last way i posted you here:
$key = randString(6);
while(mysqli_num_rows(mysqli_query($con, "SELECT id FROM table WHERE key = '".mysqli_real_escape_string($con, $key)."'")) > 0) {
$key = randString(6);
}
It will always create random 6 char key, because if it hits already existing key in db, it will re-create new one and so on, until its unique:] It is the best way for u, this way I'm also using :]
Actually the best-best way would be to generate table with all existing unique keys (62^6) * 6 bytes each key -> 317 GB if I'm not mistaken (morning) :] I dont think you will hit 1/10000 of that :]

MySQL - Fetch rows where a field value is equal to foreach value

I want to only fetch data which is related to foreach value.but em getting empty result.$userid is an array, thats why i need to use for each .Please correctify this or suggest any alternative approach.
$user_id=$_POST['uid'];
foreach($user_id as $user_idf){
$sql=mysqli_query($db3->connection,"select * from profile where uid='$user_idf'");
while($row=mysqli_fetch_array($sql)){
$num=$row['country'];
echo $num;
}
}
The one query to base is prefered. Also you've forgotten field country in you query. Try this way:
$user_id=$_POST['uid'];
$user_id = is_array($user_id)?$user_id:(array)$user_id;
if(!empty($user_id)) {
$sql=mysqli_query(
$db3->connection,
"select name, country from profile
where uid in (".implode(', ', $user_id).")"
);
while($row=mysqli_fetch_array($sql)){
$num=$row['country'];
echo $num;
}
}

Generate a Unique ID using PHP and MYSQL

Hi I am creating a system that processes and ID and a UID, The UID we are generating randomly but I am a little stuck, I need to always generate a UID that does not currently exist in the db as the field is a unique field used on the front end so as not to expose the real ID.
So to recap, I am trying to generate a unique id that does not currently exist in the DB the part I haven't got working is the cross checking in the db so it sometimes will give a number that already exists in the db even though it shouldn't thanks in advance.
This is my code so far:
function uniqueID($table)
{
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$possible = '1234567890';
$code = '';
$characters = mt_rand(7,14);
$i = 0;
while($i < $characters)
{
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
$result = $db->query('
SELECT uniqueID
FROM '.$table.'
WHERE uniqueID = "'.$code.'"
LIMIT 1
');
$totalRows = $result->num_rows;
if(!$result)
{
return $db->error;
}
else
{
if($totalRows > 0)
{
return uniqueID($table);
}
else
{
return $code;
}
}
}
http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid
To generate unic UID you can use time, i think it was a very small chanse that records will be added in the same second, with two random data.
write some function which return it to you like that
function generate_uid(){
return md5(mktime()."-".rand()."-".rand());
}
In PHP there's a function called uniqid()
http://php.net/manual/en/function.uniqid.php
I could talk about generating ids, like the others did, but this is not your question.
Your query seems fine. If it returns 0 rows but you seem to find the code in the database, then most likely it only looks the same, but actually isn't. It could be padded by whitespace.
One way to solve this is by selecting the last row of your user database and have your script to check for the id field (you can achieve this by performing a select ordering by ID in descendent mode) then you can use that info for randomize numbers greater than that ID.
EDIT
$result = $db->query('
SELECT uniqueID
FROM '.$table.'
');
$already_in_database = array();
while ($row = mysql_fetch_array($result)){
$already_in_database[] = $row['UID'];
}
$new = rand(0,$some_max_value);
while(in_array($new,$already_in_database)){
$new = rand(0,$some_max_value);
}
I figured out what the problem was already, As I mentioned to everyone the code generation was not the issue! The issue was that the cross check was not working correctly. So all I did was removed this loop
while($i < $characters)
{
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
As this was causing my unique ID to end up wrong.

Categories