Why is this PHP/mYsql not working?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
RustyDoorknobs
Forum Newbie
Posts: 15
Joined: Mon Sep 07, 2009 4:50 pm

Why is this PHP/mYsql not working?

Post 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
 
 
User avatar
Weiry
Forum Contributor
Posts: 323
Joined: Wed Sep 09, 2009 5:55 am
Location: Australia

Re: Why is this PHP/mYsql not working?

Post 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.
Post Reply