0

Im trying to update multiple rows with unique strings for each row by clicking a button. But whenever i generate them, it stores the same value. and im having an error saying "Notice: Uninitialized string offset: 60". I also want that if the unique string already exists in the database, it must create a new one. help please. more power!

here is my code:

if(isset($_POST['gen'])){
function genRandomString() {
    $length = 6;
    $characters = '023456789abcdefghijkmnopqrstuvwxyzQWERTYUIOPASDFGHJKLZXCVBNM';
    $string = '';    

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
}

    $q = mysql_query("SELECT * FROM exam_passwords WHERE pass_subject_id = ".$subject_id."")or die(mysql_error());
    $r = mysql_num_rows($q);

    for($i = 0; $i<$r; $i++){

    $random_string = genRandomString();
    $k = "UPDATE exam_passwords SET pass_password = '$random_string' WHERE pass_subject_id = '$subject_id'";
$result = mysql_query($k);

    }
}

1 Answers1

0

As strlen will return the actual number of chars in a string and treating a string as an array of chars will index that string from 0 to strlen -1 you need to,

Change this line as follows.

$string .= $characters[mt_rand(0, strlen($characters) -1 )];
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • Right. thank you for your suggestion, but could you help me how to update multiple rows with unique strings each? – Dark King Rayleigh Aug 29 '13 at 10:24
  • This may help http://stackoverflow.com/questions/688549/finding-duplicate-values-in-mysql You have to wrap your existing code looping through all the duplicates found by the code in the linked post. – RiggsFolly Aug 29 '13 at 10:29
  • Is there any other way to update my records to update multiple rows with unique strings each? – Dark King Rayleigh Aug 29 '13 at 11:01