Page 1 of 1

altering MySQL table value.

Posted: Tue Dec 30, 2003 10:48 am
by lizlazloz
uh, how do i alter a table value? for example:

id | value
----------------
1 | 5
2 | 9
3 | 2

say i want a value to increase by 1, in this case the value of id 2, then display the new value.

I wrote this code which gets the id and value, but how do i increase the value by one?

Code: Select all

<html><head><title>Page</title></head>
<body>

<?php

$conn=mysql_connect("localhost","shaun","squall")
or die("Could not conect");

$rs = mysql_select_db("game", $conn)
or die("couldnt select database");

$sql="select id,strength from game where id=$_GET[id]";

$rs=mysql_query($sql,$conn)
or die("could not execute query");

while( $row = mysql_fetch_array($rs) )
{
echo("ID: ".$row["id"]);
echo("<br>Strength: ".$row["strength"]."<br>");
}

?>
</body></html>
please help, thanks.

Posted: Tue Dec 30, 2003 11:36 am
by microthick
You'd just continue on with another query.

$newStrength = $row["strength"] + 1;

$sql = "update game set strength = ".$newStrength." where id = ".$_GET["id"];

$mysql_query($sql, $conn);

Posted: Tue Dec 30, 2003 11:57 am
by lizlazloz
thanks, I'll give it a go.

Posted: Tue Dec 30, 2003 12:23 pm
by lizlazloz
hmm, $row["strength"] + 1 doesnt seem to add 1 to the strength for me....

i just echoed newstrength, and it is always 1. so whatever strength used to be, it is made to 1.... hmm... what's up?

Posted: Tue Dec 30, 2003 12:34 pm
by microthick
If you echo $row["strength"] right before newstrength, is it a blank? Or does it output correctly?

btw, you'd want to do the query and stuff in the while loop.

Posted: Tue Dec 30, 2003 1:04 pm
by McGruff
UPDATE table SET value = value+1 WHERE ..etc..

Posted: Tue Dec 30, 2003 1:12 pm
by lizlazloz
ah, dont worry, I've got it now, it was just a case of a bit of messing around. thanks.

Posted: Tue Dec 30, 2003 1:38 pm
by lizlazloz
no i havent got it! argh, i keep thinking i ahve, then i havent....

ok well I've got this:

Code: Select all

<html><head><title>Page</title></head>
<body>

<?php

$conn=mysql_connect("localhost","shaun","squall")
or die("Could not connect");

$rs = mysql_select_db("game", $conn)
or die("couldnt select database");

$sql="update game set strength= strength + 1 where id=$_GET["id"]";

$rs=mysql_query($sql,$conn)
or die("could not execute query");

echo("strength has increased by one.");

?>
</body></html>
now what i want to happen is a user visits localhost/page.php?id=2 , or whatever id number you choose, then the id's strength increases by one. well, for some reason, the 'get' function now isnt working i think, i just get a white screen...

Posted: Tue Dec 30, 2003 1:39 pm
by lizlazloz
ah, sorry, now i have got it :D

all i had to do was remove the ""s" from around id. i feel such a fool... anyway thanks to everyoen who helped, this case is officially closed.