Note that there are some explanatory texts on larger screens.

plurals
  1. POGenerate a different random string in my for loop
    primarykey
    data
    text
    <p>I have the following function to generate a random string:</p> <pre><code>public function generateString(){ function generateCharacter () { $possible = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; $char = substr($possible, mt_rand(0, strlen($possible)-1), 1); return $char; } function generateNumber () { $GUID = generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter().generateCharacter(); return $GUID; } $string = generateNumber(); return $string; } </code></pre> <p>I then need to be able to generate these random strings x amount of times using a for loop and insert them into my MySQL table:</p> <p><code>$how_many</code> is where i would select how many times i want to loop.</p> <pre><code>for ($i = 1; $i &lt;= $how_many; $i++) { $random = $this-&gt;generateString(); $query_params = array( ':code' =&gt; $random, ); $query = " INSERT INTO table ( code ) VALUES ( :code ) "; try { $stmt = DB::get()-&gt;prepare($query); $stmt-&gt;execute($query_params); } catch(PDOException $ex) {} } </code></pre> <p>The above gives me an error though of:</p> <pre><code>Fatal error: Cannot redeclare generateCharacter() (previously declared in.... </code></pre> <p>I know i cannot have the function in the for loop otherwise i get this error but if i have it outside the loop it just generates the string once and inserts the same string everytime.</p> <p>How can i get it so each insert in my loop is a new random string?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload