Generating CDKey works, checking if exists doesnt - php

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)

Related

How to use SUBSTRING and use it on making a data unique in PHP

I am trying to do this in my PHP code, the thing is I haven't figured it out yet. I want to make the first 3 characters UNIQUE but still the data is saved. For example if I input GTX-1070 and will Input another entry named GTX-3080 it should not be saved because "GTX" was already been used. I am doing this without using unique constraint in SQL.
Here is my PHP code
<?php
include('../include/connect.php');
$control_no = "";
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$control_no = $_REQUEST['control_num'];
if(isset($_POST['subBtn']))
{
$control_no = mysql_real_escape_string($_POST["control_num"]);
$con->next_result();
$control_check_res = mysqli_query($con, "SELECT SUBSTRING(control_no, 1, 3) FROM tools_masterlist WHERE control_no = '$control_no'");
if (mysqli_num_rows($control_check_res))
{
echo '<script> $("#control_num_Modal").modal("show"); </script>';
}
else
{
$query = "INSERT INTO tools_masterlist (control_no)
VALUES ('$control_no')";
$con->next_result();
$result=mysqli_query($con,$query);
if(!$result)
{
echo '<script> $("#control_num_Modal").modal("show"); </script>';
}
else
{
echo '<script> $("#maModal").modal("show"); </script>';
}
}
}
}
?>
I have editted my code because I want to highlight the part where I coded my SUBSTRING query and the condition. I am really confused right now on what should I put in my condition thank you very much in advance for the help.
In your database, the column for "GTX" or that 3 unique character you are pertaining to, must be set in PRIMARY KEY so all data that is to be inserted is unique.

autoincrement alphanumeric in phpmyadmin mysqlserver

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;
}

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 :]

Check if the output returned by a query contains a string/number or not

I am working on Moodle but have a php-mysql related doubt which is turning out to be complicated, thanks to the lack of my knowledge.
I have a query which returns the output fine. Using IF-ELSe condition I need to check if there is a combination of one of the fields containing a string and one of the field containing a number.
The fields I m checking are of the following type in the database table.
element - varchar(255)
value - longtext
This is my query which returns the o/p as mentioned below:
Query
$scormstatus = $DB->get_records_sql("SELECT sc.*, s.name AS activityname FROM mdl_scorm_scoes_track AS sc JOIN mdl_scorm AS s ON s.id = sc.scormid WHERE sc.scormid = '" .$activityid. "' AND sc.userid = '" .$userid. "' AND sc.attempt = '".$scormattempt->attempt."'");
foreach($scormstatus as $status)
{
echo "<br/>".$status->element."**".$status->value."<br/>";
if(is_numeric($status->value))
{
if($status->element = 'cmi.core.score.raw' && $status->value != '0')
{
echo "<br/>Score";
}
else
{
if($status->element = 'x.start.time' && $status->value != '0')
{
echo "<br/>Started";
}
}
}
}
Output:
cmi.core.lesson_location**2
Score
cmi.core.lesson_status**incomplete
cmi.core.score.max**50
Score
cmi.core.score.min**0
cmi.core.score.raw**0
cmi.core.total_time**00:00:22.00
x.start.time**1334767290
Score
Now as you would have seen that even though I'm checking for a condition which is a combination of 'cmi.core.score.raw' and value greater than 0 it still prints 'Score' for all records and never goes in the else part.
Ideally the output I'm looking forward to see is something like this
IDEAL O/P:
cmi.core.lesson_location**2
cmi.core.lesson_status**incomplete
cmi.core.score.max**50
cmi.core.score.min**0
cmi.core.score.raw**0
cmi.core.total_time**00:00:22.00
x.start.time**1334767290
Started
My guess is that it isn't recognizing the value field which is a number in my IF--ELSE case and hence always ends up going in the wrong IF part.
Any guesses as to what is happening. Thanks in advance
This code:
if($status->element = 'cmi.core.score.raw'
needs to be:
if($status->element == 'cmi.core.score.raw'
A single = is for assignment, while two == is for comparison.

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