Forum Moderators: coopster

Message Too Old, No Replies

Having trouble with updating mysql database

         

SoulMaster

10:30 pm on May 28, 2008 (gmt 0)

10+ Year Member



So I have this code:

function replaceQuestion($lvl, $ques, $a, $b, $c, $d, $ans, $nr) {
$qu="UPDATE '$lvl'
SET ques = '$ques', a = '$a', b = '$b',
c = '$c', d = '$d', ans='$ans'
WHERE nr = '$nr'
";
mysql_query($qu);
}

But it doesnt seem to work. I checked that the data comes to this function clearly and the function is beeing activated, but there's no change in the database. :/ PS. I really don't know what should i quote in this code and what I shouldn't could you please explain me that too? (A)

Regards

[edited by: SoulMaster at 10:31 pm (utc) on May 28, 2008]

eelixduppy

10:56 pm on May 28, 2008 (gmt 0)



First off, I would define some sort of global $link variable that is assigned to the database connection returned by mysql_connect(). So it would be something as follows:

$link = mysql_connect('localhost', 'username', 'password');
#
#
function replaceQuestion($lvl, $ques, $a, $b, $c, $d, $ans, $nr) {
#
#then grab that variable in your function
global $link;
#
$qu= [url=http://www.php.net/sprintf]sprintf[/url]("UPDATE `%s` SET `ques` = '%s', `a` = '%s', `b` = '%s', `c` = '%s', `d` = '%s', `ans`='%s' WHERE `nr` = '%s'",
[url=http://www.php.net/mysql-real-escape-string]mysql_real_escape_string[/url]($lvl),
mysql_real_escape_string($ques),
mysql_real_escape_string($a),
mysql_real_escape_string($b),
mysql_real_escape_string($c),
mysql_real_escape_string($d),
mysql_real_escape_string($ans),
mysql_real_escape_string($nr));
#
#you should know if the update was successful or not, so return the value instead
return mysql_query($qu, $link); #you might want to add error reporting, too, for debugging
}

If this doesn't work then there is something wrong with your connection to the database, or your query itself.

[edited by: eelixduppy at 3:18 pm (utc) on May 29, 2008]

SoulMaster

11:22 am on May 29, 2008 (gmt 0)

10+ Year Member



Thank you, it made the trick. Yeah I totally forgot to escape everything, my bad.

eelixduppy

5:01 pm on May 29, 2008 (gmt 0)



Glad it works. Just to let you know, there was an error in your MySQL syntax that I am pretty sure was causing the error. You should not have single quotes around the table name,
'$lvl'
. I have added MySQL's escape character around the table name in my example, the prime character(`). So the corrected looked like the following:
`$lvl`
.

That fact that you didn't escape your variables wasn't the issue, it just could be a security issue, or just break your script completely.

Hope that helps for future projects :)

SoulMaster

5:51 pm on May 30, 2008 (gmt 0)

10+ Year Member



Yes i know that escaping them wasn't the issue. Thats why i asked about quoting at the first place. But I now realised that everything that I've already done is unescaped, wich is bad.