Jump to content

How to update 2 tables in One statement?--please help


geekisthenewsexy

Recommended Posts

hi guys, i'm trying to update 2 tables here and if possible in one go.

but i'm kinda stuck 'cause only one table gets updated..please have a look at my code (i bet think there are errors in it)..

 

i'm using php and mysql

<?php
include("dbconnection_wmsuipil.php");
$id = $_POST['id'];
$sy = $_POST['sy'];
$check=mysql_query("SELECT SchoolYear FROM tblsetsy WHERE SchoolYear='$sy'")or die (mysql_error());
	while($row = mysql_fetch_array($check)) {	
	}
	$setsy=$row['SchoolYear'];
	if($setsy==$sy)
	{
	$sql=mysql_query("UPDATE admin_sy SET school_year='$sy' WHERE id='$id'") or die(mysql_error());
	$sql=mysql_query("UPDATE tblSetSY SET SchoolYear='$sy' WHERE id='$id'") or die(mysql_error());
	}
	else{
		$sql=mysql_query("UPDATE admin_sy SET school_year='$sy' WHERE id='$id'") or die(mysql_error());
	}

?>

 

..hope you guys can help.please inform me if it's not clear..

yes, i know that. :P

i tried placing

 

 $setsy=$row['SchoolYear'];
      if($setsy==$sy)
      {
      $sql=mysql_query("UPDATE admin_sy SET school_year='$sy' WHERE id='$id'") or die(mysql_error());
      $sql=mysql_query("UPDATE tblSetSY SET SchoolYear='$sy' WHERE id='$id'") or die(mysql_error());
      }
      else{
         $sql=mysql_query("UPDATE admin_sy SET school_year='$sy' WHERE id='$id'") or die(mysql_error());
      }

inside, but i won't get any updates..so there..i didn't have errors with it though..

There's a fair bit of redundancy in there. After moving the stuff into the while loop, I can condense the whole thing down into this functionally-equivalent code:

include("dbconnection_wmsuipil.php");
$id = $_POST["id"];
$sy = $_POST["sy"];

// * your query asks for SchoolYear but only when SchoolYear=$sy
// so... why are you asking for it?
$results = mysql_query("SELECT 1 FROM tblsetsy WHERE SchoolYear='$sy' LIMIT 1");
if (mysql_num_rows($results) > 0) {
// * using a loop will only repeat the same actions over and over again
// * comparing $row[schoolYear] with $sy is pointless because, according
// to the query, SchoolYear=$sy
mysql_query("UPDATE admin_sy SET school_year='$sy' WHERE id='$id'");
mysql_query("UPDATE tblSetSY SET SchoolYear='$sy' WHERE id='$id'");
}

 

So does that make sense according to what you're trying to do?

If there are any rows in tblsetsy with the matching SchoolYear=$sy, update the admin_sy and tblsetsy tables to use that same SchoolYear for any matching id=$id

Archived

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

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.