PHP MySQL generating unique random number - php

I don't understand why my code isn't working. The connection works and everything else however when I try to generate a unique random number and check from the MySQL if the number is there it still prints out a random number but it's not UNIQUE. Could anyone help me thx?
Here's my code:
$num = rand(1,5);
$sel_query = "SELECT * FROM test";
$result2 = $con->query($sel_query);
$i = 1;
for (;$i<2; $i++)
{
while($row = mysqli_fetch_array($result2))
{
if ($row['id'] == $num)
{
$num = rand(1,5);
$i = 0;
}
}
}

This should work:
$is_unique = false;
$num = false;
while (!$is_unique){
$num = rand(1,5);
$sel_query = "SELECT id from test where id = " . $num;
$result2 = $con->query($sel_query) or die($conn->error);
if (!mysqli_fetch_array($result2)){
$is_unique = true;
}
}
echo "Unique number is " . $num;
But if there aren't any more possible unique numbers, it will loop forever.

I know this is a bit old, but I found this question after needing a similar answer. I've taken Jodes's answer and updated it slightly, so that it won't run forever, is a function that returns the number, and accepts a mysqli connection as $mysqli:
function getUniqueNumber($mysqli)
{
$is_unique = false;
$num = false;
$times_run = 0;
while (!$is_unique)
{
if($times_run > 10)
{
echo "Run too many times, dying.";
die();
}
$num = rand(1,5);
$sel_query = "SELECT id from test where id = " . $num;
$result2 = $mysqli->query($sel_query) or die($mysqli->error);
if (!mysqli_fetch_array($result2))
{
$is_unique = true;
}
$times_run++;
}
return $num;
}

Related

UPDATE MYSQL DATA ROW USING IF ELSE WITHIN FOR LOOP

I am trying to make the user send an email which is not already referred to by him with below code. But else statement updates e-mail to data even if there is already the same e-mail existing in MySQL data row.
if(isset($row)){
if (array_key_exists("email", $_POST)){
$query = "SELECT id FROM users WHERE email = '".mysqli_real_escape_string($link,$_POST['email'])."' LIMIT 1";
$ans = mysqli_query($link, $query);
if(mysqli_num_rows($ans) > 0){
$nofriend = $_POST['email']." is already registered.";
}
else{
$referredemails = $row["rfremails"];
$array = explode(",", $referredemails);
print_r($array);
for($i = 0; $i < sizeof($array); $i++){
if($array[$i] == $_POST["email"]){
$nofriend = "This e-mail is already referred by you.";
}
else{
$referdate = getdate();
$timestamp = "$referdate[mday] $referdate[month] $referdate[year]";
$opngems = $row["gems"];
$query = "UPDATE users SET rfremails = '".$referredemails.",".$_POST["email"]."', gems = '".$opngems."+1-".$timestamp."-".$_POST["email"]."' WHERE id = '".mysqli_real_escape_string($link,$_SESSION['id'])."' LIMIT 1";
mysqli_query($link,$query);
header("Location: showupdate.php");
}
}
}
}
}
it is caused by condition in for cycle
for($i = 0; $i < sizeof($array); $i++){
if($array[$i] == $_POST["email"]){
//stuff
} else {
//....$query = "UPDATE users SET rfremails =...
}
}
when user have referred more than one email this condition will be evaluated as false and thus else segment of code will be processed, resulting in update in database.
it is wise to use help variables for such cases as this. e.g.:
$noFriend = false;
for ($i = 0; $i < sizeof($array); $i++) {
if ($array[$i] == $_POST["email"]) {
$noFriend = true;
...
}
if ($noFriend === false) {
//update
}
you can also use break statement when you find first occurence of same referred email, to speed things up.

How do i verify query from mysql database before outputing record

In my code am trying to verify if query is true before outputing result i have tried:
require("init.php");
if(empty($_GET["book"]) && empty($_GET["url"])) {
$_SESSION["msg"] = 'Request not valid';
header("location:obinnaa.php");
}
if(isset($_GET["book"]) && isset($_GET["url"])) {
$book = $_GET['book'];
$url = $_GET['url'];
$drs = urldecode("$url");
$txt = encrypt_decrypt('decrypt', $book);
if(!preg_match('/(proc)/i', $url)) {
$_SESSION["msg"] = 'ticket printer has faild';
header("location:obinnaa.php");
exit();
} else {
$ql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
if($count < 1) {
$_SESSION["msg"] = 'Transation has oready been made by a customer please check and try again';
header("location:obinnaa.php");
exit();
}
while($riow = mysqli_fetch_assoc($ql)) {
$id = $riow["id"];
$tqty = $riow["quantity"];
for($b = 0; $b < $tqty; $b++) {
$run = rand_string(5);
$dua .= $run;
}
}
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$split = $dua;
$show_plit = str_split($split, 5);
$b = 0;
while($row = mysqli_fetch_assoc($sql)) {
$id = $row["id"];
$qty = $row["quantity"];
$oldB = $b;
$am = " ";
for(; $b < $oldB + $qty; $b++) {
$am .= "$show_plit[$b]";
$lek = mysqli_query($conn, "UPDATE books SET ticket='$am' WHERE id=$id");
}
if($lek) {
$adr = urlencode($adr = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$ty = encrypt_decrypt("encrypt", $txt);
$vars = array(
"book" => $ty,
"url" => $adr
);
$querystring = http_build_query($vars);
$adr = "viewbuy.php?" . $querystring;
header("location: $adr");
} else {
$_SESSION["msg"] = 'Transation failed unknow error';
header("location:obinnaa.php");
}
}
}
}
but i get to
$_SESSION["msg"]='Transation has oready been made by a customer please check and try again
even when the query is right what are mine doing wrong.
Check your return variable name from the query. You have $ql when it should be $sql.
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
A good IDE would flag this. NetBeans is a good free one.
Public Service Announcement:
NEVER build SQL queries straight from a URL parameter. Always sanitize your inputs and (better yet) use parameterized queries for your SQL calls. You can Google these topics for more info.

how to get this bit work in pdo

heyya all, well pdo is kinda new to me and i sure got no idea how to get this bit of code converted into pdo, if one of you could help me out in this would really be a great help
here is my code
$unique_ref_length = 8;
$unique_ref_found = false;
$possible_chars = "23456789BCDFGHJKMNPQRSTVWXYZ";
while (!$unique_ref_found) {
$unique_ref = "";
$i = 0;
while ($i < $unique_ref_length) {
$char = substr($possible_chars, mt_rand(0, strlen($possible_chars)-1), 1);
$unique_ref .= $char;
$i++;
}
$query = "SELECT * FROM table WHERE ref ='".$unique_ref."'";
$result = mysql_query($query) or die(mysql_error().' '.$query);
if (mysql_num_rows($result)==0) {
$unique_ref_found = true;
}
}
$ref = $unique_ref;
its fixed nevermind and thanks
$qry = "SELECT * FROM table WHERE token ='".$unique_ref."'";
$stm = $db->prepare($qry);
$stm->execute();
if ( $row = $stm->rowCount()==0) {
$unique_ref_found = true;
}

How to run a function inside a function if a condition is met

Please I've been trying to create a function that would query a DB, select from the table, and if the row count is not equal to 6, then a row from the table and repeat (or maybe duplicate) until the row count is equal to 6. I've search for this here in StackOverflow, but didn't get anything close. Please if you have a similar link to this, please post it here, and I'll give it a go.
Here's my code:
//List All active adverts
function showActiveAdverts()
{
$status = 1;
//Build final queries.
$query = mysql_query("SELECT * FROM table WHERE
status = '".mysql_real_escape_string($status)."' ORDER BY rand() LIMIT 6") or die(mysql_error());
$count = mysql_num_rows($query);
$row = mysql_fetch_assoc($query);
# My question here, check if the $count >= 1 && $count != 6, then do getDefaultBannner() and repeat it until it runs for 6 times.
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}
Here's the code for getDefaultBannner()
function getDefaultBannner()
{
$status = 6;
$query = mysql_query("SELECT id FROM table WHERE status = '".mysql_real_escape_string($status)."' ")
or die(mysql_error());
$count = mysql_num_rows($query);
$row = mysql_fetch_assoc($query);
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}
Thanks in advance!
You can rewrite your code as this
//List All active adverts
$query = mysql_query("SELECT * FROM table WHERE
status = '".mysql_real_escape_string($status)."' ORDER BY rand() LIMIT 6") or die(mysql_error());
$count = mysql_num_rows($query);
if($count >= 1 && $count != 6)
$list = getDefaultBannner();
else
$list = showActiveAdverts($query);
function showActiveAdverts($query)
{
$status = 1;
//Build final queries.
$row = mysql_fetch_assoc($query);
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}

Do-while loop hangs the connection to website

I am trying to use do-while loop to check if a value exists in database,
function check($a) {
$query = "SELECT * FROM `table` WHERE code = '$a'";
$result = mysql_query($query);
$nm = mysql_num_rows($result);
if ($nm > 0) {
return true;
} else {
return false;
}
}
function randomnumber() {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 10) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
$number = randomnumber();
do { $number = randomnumber(); } while (!check($number));
That codes somehow hangs the connection to website. After i execute this page, strangely it cannot connects to website until i restart the browser.
What may cause this ?
your query is never evaluating to true, so the loop is infinite. As long as it's not pulling back any rows where code = 'yourRandomNumber', then you will be looping indefinitely.
If you want to simply select a random 'code' from your database this code will be much more efficient than what you've got.
$query = 'SELECT DISTINCT code FROM `table`';
$result = mysql_query($query);
$my_arr = array();
while($row = $mysql_fetch_assoc($result)) {
$my_arr[] = $row['code']
}
$random_key = $my_arr[array_rand($my_arr)];
Re-reading your question and comments I'm less and less sure what your code originally set out to accomplish, if you could be a bit more clear on your objective here we could probably give you some advice on how to accomplish your goal more efficiently.
Edit:
This code will retrieve all of the codes already used in your table, calculate the difference from the possible codes, and then return one random unused code. No loop required. [well one loop, but it's a short one]
$psbl_codes = str_split("abcdefghijkmnopqrstuvwxyz023456789");
$query = 'SELECT DISTINCT code FROM `table`';
$result = mysql_query($query);
$used_codes = array();
while($row = $mysql_fetch_assoc($result)) {
$used_codes[] = $row['code']
}
$unused_codes = array_diff($psbl_codes, $used_codes);
echo "random unused code: " . $unused_codes[array_rand($unused_codes)];

Categories