Reputation: 161
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
Upvotes: 0
Views: 524
Reputation: 15379
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;
Upvotes: 1
Reputation: 204756
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.
Upvotes: 0