Create random string, check against database, if found run again - Code not functioning as I expected?
This is somewhat a continuation of this post
I've taken the following code and somewhat adapted it to my needs;
function makeString() {
// Create our random string
$string = "";
$characters = array('a', 'b', 'c', 'd');
for ($i = 0; $i < 4; $i++) {
$string .= $characters[mt_rand(0, 4)];
}
$query = "SELECT COUNT(*)
FROM myTable
WHERE string = '{$string}'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row['COUNT(*)'] > 0) { // if it already exists, do it again
$string = makeString();
}
return $string;
}
My version:
function valCode() {
$num1 = mt_rand(1, 6);
$valcode = $num1;
include("dbdata.php");
$conn = mysql_connect($db_host, $db_uname, $db_pword) or die("Couldn't connect because ".mysql_error());
mysql_select_db($db_name);
$query = "SELECT COUNT(*) FROM 开发者_如何学运维records WHERE valcode='{$valcode}'";
$result = mysql_query($query) or die("Query failed because ".mysql_error());
$row = mysql_fetch_assoc($result);
if($row['COUNT(*)'] > 0) {
$valcode = valCode();
}
$query2 = "INSERT INTO records (valcode) VALUES ($valcode)";
$result2 = mysql_query($query2) or die("Query failed because ".mysql_error());
return $valcode;
}
valCode();
Rather than creating a random string (an int in the example), checking it against the database, then running it again if found, this runs the script twice, inserting duplicate values into my table.
I thought perhaps this could because of the use of a Primary Key allowing two of the same values to be placed in under different Primary Keys, thus ID'ing them as uniques, but in truth I really have no idea.
Any help or comments would be very much appreciated!
It's doing what your code says to do. Every call to valCode()
will execute one INSERT
query because that's part of the function.
An example run-through of your code:
- You call
valCode()
to start looking for a new code valCode()
generates a code and finds it already exists, so it callsvalCode()
againvalCode()
generates a code and finds it already exists, so it callsvalCode()
againvalCode()
generates a unique code,INSERT
s it into the database, and returns to its caller (the second call of the function)- The second call of
valCode
nowINSERT
s the code and returns to its caller (the first call of the function) - The first call of
valCode
nowINSERT
s the code and returns to its caller (the end of your code)
You need to move the INSERT
outside of the function and use its return value in the query.
精彩评论