Page 1 of 1

Why is this PHP/mYsql not working?

Posted: Tue Oct 06, 2009 6:48 pm
by RustyDoorknobs
Hers my code

Code: Select all

 
function genRandomString() {
$length = 10;
$characters = "0123456789abcdefghijklmnopqrstuvwxyz";
 
 
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
 
return $string;
}
genRandomString();
 
mysql_select_db("DATABASE", $con);
$sql = "INSERT INTO hits VALUES ('3', " . $string . ")";
mysql_query($sql);
 
 
/////////////////some variables are defined elsewhere
 
 

Re: Why is this PHP/mYsql not working?

Posted: Tue Oct 06, 2009 7:08 pm
by Weiry
try changing these 2 lines.

Code: Select all

 
$sql = "INSERT INTO `hits` VALUES ('3', '{$string}')";
mysql_query($sql,$con);
 
the '{$string}' will help prevent SQL Injection, your current code could be exposed to an injection as is.
also, you may want to look here in your code.

Code: Select all

genRandomString();
you are calling a function which returns $string.
That is fine, but $string only exists inside the genRandomString() function.
you need to make a new variable $string outside of the function.

Code: Select all

$string = genRandomString();
now you have a variable $string which is the returned value of genRandomString() which you can now use to insert into your database.