Do-while loop hangs the connection to website - php

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

Related

database query, compare each two rows but getting only first two rows

Hi i am querying my db so that i can compare every two rows. ex 1 and 2, then 2 and 3, then 3 and 4. and so on and so forth. but it only compares the first two rows. any ideas? here is my code:
$result = mysql_query("SELECT *FROM attendance ORDER BY pid ASC") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// $response["nominees"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$prev_sid = $row["sid"];
$prev_pid = $row["pid"];
$row2 = mysql_fetch_array($result);
if($row2["pid"] == $prev_pid){
if(($row2["sid"] - $prev_sid) == 1){
$attended_elec = mysql_query("SELECT pid FROM election_attendance where election_id = '$election_id'");
if(mysql_num_rows($attended_elec) > 0){
$not_officer = mysql_query("SELECT usertype FROM users WHERE pid = '$prev_pid'");
if(mysql_result($not_officer, 0) == "member"){
// echo "PID" . $prev_pid;
// $nominee["pid"] = $row2["pid"];
$user_details = mysql_query("SELECT *FROM users WHERE pid = '$prev_pid'");
if(mysql_num_rows($user_details) > 0){
$response["nominees"] = array();
while ($row3 = mysql_fetch_array($user_details)) {
$nominee = array();
$nominee["pid"] = $row3["pid"];
$nominee["firstname"] = $row3["firstname"];
$nominee["lastname"] = $row3["lastname"];
$nominee["gender"] = $row3["gender"];
$nominee["contact"] = $row3["contact"];
$nominee["email"] = $row3["email"];
$nominee["address"] = $row3["address"];
$nominee["institution"] = $row3["institution"];
$nominee["points"] = $row3["points"];
$nominee["usertype"] = $row3["usertype"];
// push single product into final response array
array_push($response["nominees"], $nominee);
}
}
}
}
}
}
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "There is no candidate yet from the records.";
// echo no users JSON
echo json_encode($response);
}
thanks in advance, have a nice day
Theres a problem right at the while(), you're fetching the 1st row, and is correct.
Then, inside it you fetch the 2nd, which is what you intend, but when the iteration is repeating, the while will fetch the 3rd, and the inner the 4th, so you lost there the comparisson between 2nd and 3rd.
// fetch data from DB
$results = "...";
if (mysql_num_rows($result) < 1)
{
// no products found tell your users
return;
}
// lets make some variables to walk through the list
$previous = mysql_fetch_array($results);
$actual = null;
// and now lets walk through the list
while($actual = mysql_fetch_array($results))
{
// execute your logic here
// than at the end move the actual row to become the previous
$previous = $actual;
}
NOTICE you shouldn't use mysql_ * methods they're are deprecated. you can use the brother mysqli_ * or PDO
I would do something like this? But there is almost certainly a less resource intensive way to do it.
$x = 0;
$y = 1;
$total = mysql_num_rows(mysql_query("SELECT * FROM `the_place`");
while ($x < $total AND $y < total){
$query1 = "SELECT * FROM `the_place` LIMIT $x,1";
$query2 = "SELECT * FROM `the_place` LIMIT $y,1";
$row1 = mysql_fetch_array(mysql_query($query1);
$row2 = mysql_fetch_array(mysql_query($query2);
// Do comparison here
if ($row1 == $row2){
// etc
}
$x = $x++;
$y = $y++;
}

PHP MySQL generating unique random number

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

Why won't this loop variable increment?

I'm trying to write code that will count the number of users returned by a sqlite query and then split a 'bill' between those users, but for some reason my counter won't increment and I am getting a division by zero error. My code is here:
<?php
session_start();
require 'database.php';
$db = new Database();
$name = $_POST['name'];
$amount = $_POST['amount'];
$due = $_POST['due'];
$gid = $_GET['gid'];
$uid = $_SESSION['id'];
$count = 0;
$users = $db->query("select * from members where(gid='$gid');");
while($data = $users->fetchArray()) {
$count++;
}
$amount = $amount / $count;
while($data = $users->fetchArray()) {
if($data['uid'] == $uid) {
continue;
} else {
$temp = $data['uid'];
$db->exec("insert into bills values(NULL,'$gid','$uid','$temp','$amount','$due','false','$name');");
}
}
header('Location:grouppage.php?gid='.$gid.'');
?>
Anyone have any ideas on how to fix this?
Regardless of the loop not seeming to work, you can't have two while(... fetchArray()) loops without something resetting the internal pointer.
In this case, however, you don't need that:
$users = $db->query("select * from members where(gid='$gid')");
$count = $users->numRows();
if( $count == 0) die("No users found!");
$amount /= $count;
while($data = $users->fetchArray()) {
...
}
You don't handle case, when select doesn't return any record.
Just look at your code:
$users = $db->query("select * from members where(gid='$gid');");
while($data = $users->fetchArray()) {
$count++;
}
No data selected -- no while-body
executed, $count not incremented and left zero, with "divide by zero" error in following line as consequence.
$amount = $amount / $count;

How to 'append' function variables using the URL and a question about Array's

The first question is how to run a function using the URL, I have the following function:
function do_curl($start_index,$stop_index){
// Do query here to get all pages with ids between start index and stop index
$query = "SELECT * FROM xxx WHERE xxx >= $start_index and xxx <= $stop_index";
Now when I'm trying to do curl.php?start_index=0&stop_index=2 this is not working but when i delete the function and WHERE idnum = 1 it is working.
Now the second question is how 'compile' all the fields from the rows to arrays? I have the current code:
$query = "SELECT * FROM fanpages";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$fanpages_query = '\'http://graph.facebook.com/'.$row['page_id'].'\', ';
echo $fanpages_query;
}
$fanpages = array($fanpages_query);
$fanpages_count = count($fanpages);
echo $fanpages_count;
echo $fanpages_query; returning
'http://graph.facebook.com/AAAAAA', 'http://graph.facebook.com/BBBBBBB', 'http://graph.facebook.com/CCCCCCCC',
(I don't have an idea how to do it in a different way, also when im doing it in such a way i can't delete the final comma which will return PHP-error.)
echo $fanpages_count; returns 1 and like you can see i have 3 there.
Thanks in advance guys!
Do a function call to do the query
function do_curl($start_index, $stop_index){
...
}
$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
For your second question, you can use arrays and the implode function to insert commas:
while ($row = mysql_fetch_array($result))
{
$fanpages_query[] = 'http://graph.facebook.com/'.$row['page_id'];
}
return $fanpages_query;
Then use implode to print them out:
echo implode(',', $fanpages);
The whole code:
function do_curl($start_index = 0, $stop_index = null) {
$queryIfThereIsNoStartIndex = '';
$queryIFThereIsNoStopIndex = '';
$queryIfBothStartAndStopIndexAreMissing = '';
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$fanpages_query[] = 'http://graph.facebook.com/'.$row['page_id'];
}
return $fanpages_query;
}
$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
$fanpages_count = count($fanpages);
echo implode(',', $fanpages);
And you should totally use mysql_escape_string for escaping the values you add to the query.

php function with a while-loop

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()).

Categories