开发者

Updating an integer defined column in a MySQL DB with PHP

I have a ta开发者_运维百科ble defined like this:

create table users (
  id int(10),
  age int(3),
  name varchar (50)
)

I want to use a query to update just age, which is an integer, that comes from an html form.

When it arrives to the method that updates it, it comes as a string, so I change it to integer with PHP and try to update the table, but it doesn't work

$age = intval($age);
$q2 = "UPDATE users SET age='$age'  where username like '$username';";
mysql_query($q2,$con);


Your query uses the field username, but your CREATE statement says name

Also, you should really look into using prepared statements to avoid SQL injection attacks (if someone provides the username ' OR 1=1;-- things are going to break). Finally, is there a reason you're doing username LIKE '$username' instead of just username = '$username'? If $username has no %s in it it amounts to the same thing


No need to cast your $age string to an integer.

More importantly, use mysql_real_escape_string() to protect against SQL injection.

$q2 = "UPDATE users SET age = " . mysql_real_escape_string($age, $con)
    . " WHERE name = '" . mysql_real_escape_string($username, $con) . "'";
mysql_query($q2, $con);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜