0

I have a question, how can I create a random string in PHP and check on a SQL if the string exist, if exist, create a new one, but if it doesnt exist use it

I have this code to create the random string:

$original_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$random_string = get_random_string($original_string, 14);
echo $random_string;

And the MySQL I would like to check if the random string is already been use is this one:

CREATE TABLE `en_videos` (
  `id` int(11) NOT NULL auto_increment,
  `name` text,
  `code` text,
  `description` text,
  `hits` int(11) default NULL,
  `program` int(11) default NULL,
  `lenght` int(11) default NULL,
  `hd` int(11) NOT NULL default '1',
  `subtitles` int(11) NOT NULL default '1',
  `type` text NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

I would like to check if the random string exists on the code field

2 Answers 2

1

Try:

$original_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$random_string = '';

do {
    $random_string = get_random_string($original_string, 14);
} while ($mysqli->query('SELECT 1 FROM `en_videos`
             WHERE `code` = "' . $random_string . '"')->fetch_row());

echo $random_string;

This assume you're using the mysqli library. If not, use whatever fetches rows as your condition handler.

Assuming you're using the mysql_* functions (in which case, I suggest you look into other mysql libraries):

$original_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$random_string = '';

do {
    $random_string = get_random_string($original_string, 14);
} while ($mysql_num_rows(mysql_query('SELECT 1 FROM `en_videos`
             WHERE `code` = "' . $random_string . '"')));

echo $random_string;
Sign up to request clarification or add additional context in comments.

2 Comments

I try using the code, and didnt work :( enteratenorte.com/admon/test.php
Try the second example (assuming you're using mysql_*)
0
select count(*) as found_num
from en_videos
where `code` = '$random_string'

returns 0 if the string was not found and > 0 if it was.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.