php function with a while-loop - php

I have a function that generates a random combination.
my function looks like this:
function random_gen($length) {
$random= "";
srand((double)microtime()*1000000);
$char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$char_list .= "abcdefghijklmnopqrstuvwxyz";
$char_list .= "1234567890";
// Add the special characters to $char_list if needed
for($i = 0; $i < $length; $i++)
{
$random .= substr($char_list,(rand()%(strlen($char_list))), 1);
}
return $random;
}
$new_url = random_gen(6);
Now i would like to have a while-loop that checks if $new_url already exist in my database...
And then insert the result like this:
mysql_query("INSERT INTO lank (url, code) VALUES ('$url', '$new_url')");
I got everything to work except the while-loop. and i just cant figure out how to do it...

define your code field as UNIQUE in your database
generate a code and run an INSERT
check with mysql_affected_rows() if the INSERT actually happened or not (i.e. code already present)
saves you a SELECT query
while ( true ) {
$new_url = random_gen(6);
mysql_query("INSERT INTO lank (url, code) VALUES ('$url', '$new_url')");
if ( mysql_affected_rows() )
break;
}

Use this random_generator
function random_gen($length) {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $characters[rand(0, strlen($characters) - 1];
}
return $string;
}

You don't need a while loop, just perform a query
mysql_query("SELECT COUNT(*) FROM lank WHERE code = {$new_url}");

It's pretty straight forward:
$sql = "SELECT COUNT(*) as num FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
while($row['num'] > 0) {
$new_url = random_gen(6);
$sql = "SELECT COUNT(*) as num FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
}

This should work, without repeating code:
while(true) {
$new_url = random_gen(6);
$sql = "SELECT COUNT(*) FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
if (!$row[0])
break;
}

Use the uniqid() function instead. It will always generate a random result.
If you need more security (i.e.: you don't want adjacent values), simply hash the output: sha1(uniqid()).

Related

how to find out last_insert_id in useing Only my_sql ...?

$query1 = "INSERT INTO `user_order` (user_id,product_id,cart_id,product_name,product_quantity,number_of_item,total,shipping_charge,discount,total_net_amount) VALUES
('$user_id','$Productid','$Cartid','$Product_name','$Quantity','$Total_Number_of_Items','$Total','$Shipping_charge','$Discount','$Total_amount')";
$run_product = mysql_query($query1);
$last_id = mysql_insert_id();
Use LAST_INSERT_ID() function
SELECT LAST_INSERT_ID() from user_order;
i find out solution...
Add to RandomString
Post.php
function generateRandomString($length = 30) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
if(){$dataObj->generateRandomString());}else{
echo ResponseClass::successResponseInArray("data", null, "0" ,"data missing","False");}}
then apiclass.php pass values
$sql = "SELECT * FROM user_order WHERE user_id = '$user_id' AND product_id = '$Productid' AND r_number = '$generateRandomString'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$only_last_id = $row['order_id'];
** find out last insert ID :)
LAST_INSERT_ID() should do the trick in a mysql console . though i would strongly suggest you to not use the old mysql connector you are currently using and Switch to PDO.

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

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)];

php cannot work with a substring

I`m making a php file to generate users and inserting them in a database. The first thing I made is to obtain the latest one and save it in a variable, then, I use a function to obtain the integer part of the string and increment that value by one, but that is the part that I think is not working.
This is the code:
<?php
$con = new mysqli('localhost', 'root', '', 'prueba');
function create_user($var){
$prefix = "U";
for($i = 0; $i < 5- strlen((String)$var); $i++) {
$prefix .= '0';
}
$var = mb_substr($var, 1);
if(is_numeric($var)) {
$int = $var++;
$var = $prefix . $int;
}
return $var;
}
$execute = mysqli_query($con, "select id_user from usuarios
WHERE id_user=(SELECT MAX(id_user) FROM usuarios)");
$row = mysqli_fetch_array($execute);
print_r($row['id_user']);
$var1 = $row['id_user'];
$userid=create_user($var1);
mysqli_query($con, "insert into usuarios (password, descripcion, id_user)
values ('A12345a', 'hgfhdgfh', ' $userid' )");
echo "hecho";
?>
Any help, please?
Change this line:
$int = $var++;
to:
$int = ++$var;
It's assigning the value of $var before incrementing.

Dynamic Update MySql Table

I am attempting to Dynamically update a MySql table, the $query looks correct when i echo it, but for some reason it dose not work when i insert the code into the MySql Query.
$b = 1;
$query_a = array();
$vars = array();
$result = mysql_query("SELECT * FROM my_table");
for ($i = 0; $i < mysql_num_fields($result); $i++) {
$vars[] = mysql_field_name($result,$b);
$b++;
}
foreach ($vars as $v)
{
if (isset($_GET[$v]))
{
$isclean = $_GET[$v];
$query[] = $v.' = '.$isclean.'';
}
}
$query = implode(',', $query);
mysql_query("UPDATE my_table SET $query WHERE UIN = '1'");
Without knowing your data types, my guess is it's because you're not adding single quotes around your values. You probably want something like:
$query[] = $v.' = \''.$isclean.'\'';

Categories