Jump to content

Getting Data To Manipulate From A Database


Guest Dazuti

Recommended Posts

I have the following code that prints the data to the screen, but I need to manipulate the variable that is the result, but I'm not sure how the information is being stored. If I just echo the variable name $result I get the following errorResource id #3Please can someone come to my assistance.The aim of the exercise was trying to teach myself how to manipulate data from databases. Sadly I didn't get far. <?phpmysql_connect("localhost","root","miller123miller") or die("Cannot connect : " . mysql_error());mysql_select_db("photorace");$query="SELECT `Tokens` FROM `tokens` WHERE `CompNumber` ='2'";$result = mysql_query($query); if($result){while($row=mysql_fetch_array($result)){echo $row[0]."<br />";}echo "all done!<br />";}echo $result; (this is the bit that causes the error)mysql_free_result($result); ?> The idea is to grab the number of tokens and add another number to it, then return the data to the database.I will get the hang of it eventually I am sure.CheersKevin

Link to comment
Share on other sites

If you want to manipulate the variable, do that before you echo out row[0] from the WHILE loop. If you want to save the changed variable, you will have to save it the database using another query. That can be also be done inside the WHILE loop. I'm not quite sure on this, but you get that error when you echo $result because PHP cannot display or change the variable info in that format.

<?phpmysql_connect("localhost","root","miller123miller") or die("Cannot connect : " . mysql_error());mysql_select_db("photorace");$query="SELECT `Tokens` FROM `tokens` WHERE `CompNumber` ='2'";$result = mysql_query($query);if ($result) {  while ($row=mysql_fetch_array($result)) {	$token = $row[0] + 5;	mysql_query("UPDATE tokens SET Tokens='$token' WHERE CompNumber='2'");	echo "5 was added to $row[0] - $token was saved to the database.<br />";  }  echo "all done!<br />";}mysql_free_result($result);?>

Link to comment
Share on other sites

You can also use array_push() to store the ouput data:

mysql_connect("localhost","root","miller123miller") or die("Cannot connect : " . mysql_error());mysql_select_db("photorace");$query="SELECT `Tokens` FROM `tokens` WHERE `CompNumber` ='2'";$DBtokens = Array();$result = mysql_query($query); if($result){  while($row=mysql_fetch_array($result))  {	array_push($DBtokens, $row);		echo $row[0]."<br />";  }  echo "all done!<br />";}

You now have the $row array stored as $DBtokens. Now you can simply retreive the data by using a foreach loop for example. It is not possible to use a result set more then one time. So you have to do it either my way or RahXephons way.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...