Page 1 of 1

Combining Code

Posted: Thu Feb 23, 2006 12:58 pm
by psurrena
How would I combine both of these statements? It seems a bit redundant that I have to connect to the same server / database twice on the same page. Assuming both sets of variables were in order, would " } else { " do it?

Thank you,
Peter

Code: Select all

<?php
			$usr = "administrator";
			/*$pwd = ";";*/
			$db = "test";
			$host = "localhost";
			
			# connect to database
			$cid = mysql_connect($host,$usr/*,$pwd*/);
			if (!$cid) { echo("ERROR: " . mysql_error() . "\n"); } 
		
			# setup SQL statement
			$SQL = " SELECT * FROM upload2 ORDER by ID";
			$SQL = $SQL .
		
			# execute SQL statement
			$retid = mysql_db_query($db, $SQL, $cid) or die(mysql_error());
		
			# display results
			$output .= "<P><DT><B>$category</B><BR>\n\n";
			$output .= "<table>\n\n";
			$howmany = mysql_num_rows($retid);
			$rowmax = 5;
			
			for($x = 0; $row = mysql_fetch_array($retid); $x++) {
				if($x % $rowmax == 0)
				$output .= "<tr>\n";
				/*$name = $row["name"];*/
				$path = $row["path"];		
				$output .= "<td><a href=\"$path\"><img src =\"phpThumb.php?src=$path&q=60&sx=120&sy=130&sw=80&sh=80&fltr[]=gray&fltr[]=rcd|8|1\" border=\"0\"></a></td>";
				if($x % $rowmax == $rowmax - 1)
				$output .= "\r</tr>\n\n";
			}
			
			if($left = (($howmany + $rowmax - 1) % $rowmax))
			$output .= '<td colspan="' . $left . '"' . ";</td>\n</tr>\n\n";
			
			$output .= "</table>\n\n";
			
			$output .= "</DT></P>";
			
			echo $output; 
		?>
		
		<hr>
		
		<?php 
			mysql_connect("localhost","administrator"/*,"password"*/); 
				
			mysql_select_db("test"); 
			
			if(!isset($cmd)) 
			{
			   $result = mysql_query("select * from upload2 order by id"); 
			   
			   while($r=mysql_fetch_array($result)) 
			   { 
				  $name=$r["name"];
				  $id=$r["id"];
				 
				  echo "<font color=\"#333333\"><b>$id</b> $name</font>";
				  echo "<br>";
				}
			}
		?>

Posted: Thu Feb 23, 2006 2:12 pm
by chrys
You should have a seperate file...

put the database connection code in another file, say database.php

then at the top of any file that needs it at all

require( "database.php" );