Page 1 of 1

Database Problem [SOLVED]

Posted: Thu Oct 28, 2004 6:55 am
by grahamd
Hey guys,

I'm having a problem with my PHP/MySQL driven site where on some pages when I add data to the database I get a "No Database Selected" error message appearing onscreen. The information adds ok and everything works fine - it's just this error message appearing for users which is bugging me! Does anyone have any idea why this would be appearing even though the site is working fine?

Cheers!

Graham 8)

Posted: Thu Oct 28, 2004 8:09 am
by patrikG
post the relevant code, please,

Posted: Thu Oct 28, 2004 10:13 am
by pickle
Without the code it's difficult to debug, but as for a stab in the dark, I'd suggest checking your error checking. If the database is selected and information is being added to that database, then the logic that outputs that error, is clearly having a problem.

Posted: Thu Oct 28, 2004 10:25 am
by grahamd
The code for one of the pages which gives me that error is:

Code: Select all

<?php # admin_editfield.php
// This page allows the editing of profile information


// Include the configuration file for error management and such.
require_once ('includes/config.inc'); 


// Set the page title and include the HTML header.
$page_title = 'Edit User Profile';
include_once ('includes/header.html');


require_once ('../mysql_connect.php'); // Connect to the database.

$query = "SELECT $_GET[field], username FROM users WHERE user_id=$_GET[id]";		
$result = @mysql_query ($query); // Run the query.
while ($row = mysql_fetch_array($result, MYSQL_NUM)) 
	{
	 $original = $row[0];
	 $username = $row[1];
	}



if($_GET[field] == "location")
{

if(isset($_POST['submit']))
 { 

	 if (isset($_POST['location']))
		{
		 $new = $_POST['location'];

			if ($new == $original)
			 {
			  $new = FALSE;
			  echo "<p><font color="red">Please enter a new value (they currently match) or click CANCEL</font></p>";
			 }
		}

	
	 if ($new)
		{
		 require_once ('../mysql_connect.php');
		 $query = "UPDATE users SET location='$new' WHERE user_id=$_GET[id]";
		 $result = @mysql_query ($query); // Run the query.
		 

		   if (mysql_affected_rows() == 1) { // If it ran OK.
			{
			 $original = $new;
			}

		 mysql_close(); // Close the database connection.
		
		}
	          else
		{
		  echo "<p><font color="red">Please select a different value or click CANCEL to go back</font></p>";
		}
}
}


if ($_GET[field] == "location")
	{

	 echo "<h3>Change Your Location</h3>

	<h5>You can change the registered <b>location</b> for user $username (ID number $_GET[id]) on this page.</h5>

	<p>
	Select a new country from the dropdown box and click CONFIRM to update the database, or click CANCEL to go back to the profile<br /><br /><br /><br />

	The current value in the database is: <b>$original</b> <br />	

	


	<form action="" method="post">
	<fieldset><br />

	<table>

	<tr>
	<td><div class="p2">New Value: &nbsp;</div></td>	


<td><select name="location" size="1">								
<option>United Kingdom</option>
<option>United States</option>
<option>Afghanistan</option>
<option>Albania</option>
<option>Algeria</option>
<option>Andorra</option>
<option>Angola</option>
<option>Antigua and Barbuda</option>
<option>Argentina</option>
<option>Armenia</option>
<option>Australia</option>
<option>Austria</option>
<option>Azerbaijan</option>
<option>Bahamas</option>
<option>Bahrain</option>
<option>Bangladesh</option>
<option>Barbados</option>
<option>Belarus</option>
<option>Belgium</option>
<option>Belize</option>
<option>Benin</option>
<option>Bhutan</option>
<option>Bolivia</option>
<option>Bosnia and Herzegovina</option>
<option>Botswana</option>
<option>Brazil</option>
<option>Brunei</option>
<option>Bulgaria</option>
<option>Burkina Faso</option>
<option>Burma/Myanmar</option>
<option>Burundi</option>
<option>Cambodia</option>
<option>Cameroon</option>
<option>Canada</option>
<option>Cape Verde</option>
<option>Central African Republic</option>
<option>Chad</option>
<option>Chile</option>
<option>China</option>
<option>Colombia</option>
<option>Comoros</option>
<option>Congo</option>
<option>Congo, Democratic Republic of</option>
<option>Costa Rica</option>
<option>Cote d'Ivoire/Ivory Coast</option>
<option>Croatia</option>
<option>Cuba</option>
<option>Cyprus</option>
<option>Czech Republic</option>
<option>Denmark</option>
<option>Djibouti</option>
<option>Dominica</option>
<option>Dominican Republic</option>
<option>East Timor</option>
<option>Ecuador</option>
<option>Egypt</option>
<option>El Salvador</option>
<option>Equatorial Guinea</option>
<option>Eritrea</option>
<option>Estonia</option>
<option>Ethiopia</option>
<option>Fiji</option>
<option>Finland</option>
<option>France</option>
<option>Gabon</option>
<option>Gambia</option>
<option>Georgia</option>
<option>Germany</option>
<option>Ghana</option>
<option>Greece</option>
<option>Grenada</option>
<option>Guatemala</option>
<option>Guinea</option>
<option>Guinea-Bissau</option>
<option>Guyana</option>
<option>Haiti</option>
<option>Honduras</option>
<option>Hungary</option>
<option>Iceland</option>
<option>India</option>
<option>Indonesia</option>
<option>Iran</option>
<option>Iraq</option>
<option>Ireland</option>
<option>Israel</option>
<option>Italy</option>
<option>Jamaica</option>
<option>Japan</option>
<option>Jordan</option>
<option>Kazakstan</option>
<option>Kenya</option>
<option>Kiribati</option>
<option>Korea, North</option>
<option>Korea, South</option>
<option>Kuwait</option>
<option>Kyrgyzstan</option>
<option>Laos</option>
<option>Latvia</option>
<option>Lebanon</option>
<option>Lesotho</option>
<option>Liberia</option>
<option>Libya</option>
<option>Liechtenstein</option>
<option>Lithuania</option>
<option>Luxembourg</option>
<option>Macedonia</option>
<option>Madagascar</option>
<option>Malawi</option>
<option>Malaysia</option>
<option>Maldives</option>
<option>Mali</option>
<option>Malta</option>
<option>Marshall Islands</option>
<option>Mauritania</option>
<option>Mauritius</option>
<option>Mexico</option>
<option>Micronesia</option>
<option>Moldova</option>
<option>Monaco</option>
<option>Mongolia</option>
<option>Morocco</option>
<option>Mozambique</option>
<option>Namibia</option>
<option>Nauru</option>
<option>Nepal</option>
<option>Netherlands</option>
<option>New Zealand</option>
<option>Nicaragua</option>
<option>Niger</option>
<option>Nigeria</option>
<option>Norway</option>
<option>Oman</option>
<option>Pakistan</option>
<option>Palau</option>
<option>Panama</option>
<option>Papua New Guinea</option>
<option>Paraguay</option>
<option>Peru</option>
<option>Philippines</option>
<option>Poland</option>
<option>Portugal</option>
<option>Qatar</option>
<option>Romania</option>
<option>Russian Federation</option>
<option>Rwanda</option>
<option>Saint Kitts and Nevis</option>
<option>Saint Lucia</option>
<option>Saint Vincent and the Grenadines</option>
<option>Samoa</option>
<option>San Marino</option>
<option>Sao Tome and Principe</option>
<option>Saudi Arabia</option>
<option>Senegal</option>
<option>Seychelles</option>
<option>Sierra Leone</option>
<option>Singapore</option>
<option>Slovakia</option>
<option>Slovenia</option>
<option>Solomon Islands</option>
<option>Somalia</option>
<option>South Africa</option>
<option>Spain</option>
<option>Sri Lanka</option>
<option>Sudan</option>
<option>Suriname</option>
<option>Swaziland</option>
<option>Sweden</option>
<option>Switzerland</option>
<option>Syria</option>
<option>Taiwan</option>
<option>Tajikistan</option>
<option>Tanzania</option>
<option>Thailand</option>
<option>Togo</option>
<option>Tonga</option>
<option>Trinidad and Tobago</option>
<option>Tunisia</option>
<option>Turkey</option>
<option>Turkmenistan</option>
<option>Tuvalu</option>
<option>Uganda</option>
<option>Ukraine</option>
<option>United Arab Emirates</option>
<option>Uruguay</option>
<option>Uzbekistan</option>
<option>Vanuatu</option>
<option>Vatican City</option>
<option>Venezuela</option>
<option>Vietnam</option>
<option>Yemen</option>
<option>Yugoslavia</option>
<option>Zambia</option>
<option>Zimbabwe</option>
</select>
</td>
</tr>	


<tr>
<td colspan="2">&nbsp;</td>
</tr>

<tr>
<td><input type="submit" name="submit" style="background-color: #F3F3F3;" value=" Confirm Change " /></td> 
<td><input type="button" style="background-color: #F3F3F3;" value=" Back to Profile " onclick="window.location.href='admin_editprofile.php?id=$_GET[id]&name=$username'" /></td> 
</tr>

</table>

</form>

</p>";	

}
}








if($_GET[field] == "level")
{

if(isset($_POST['submit']))
 { 

	 if (isset($_POST['level']))
		{
		 $new = $_POST['level'];

			if ($new == $original)
			 {
			  $new = FALSE;
			  echo "<p><font color="red">Please enter a new value (they currently match) or click CANCEL</font></p>";
			 }
		}

	
	 if ($new)
		{
		 $query = "UPDATE users SET level='$new' WHERE user_id=$_GET[id]";
		 $result = @mysql_query ($query); // Run the query.
		 

		   if (mysql_affected_rows() == 1) { // If it ran OK.
			{
			 $original = $new;
			}

		 mysql_close(); // Close the database connection.
		
		}
	          else
		{
		  echo "<p><font color="red">Please select a different value or click CANCEL to go back</font></p>";
		}
}
}


if ($_GET[field] == "level")
	{

	 echo "<h3>Change Your Applikation User Level</h3>

	<h5>You can change the registered <b>level</b> for user $username (ID number $_GET[id]) on this page.</h5>

	<p>
	Select a new level from the dropdown box and click CONFIRM to update the database, or click CANCEL to go back to the profile<br /><br /><br /><br />

	The current value in the database is: <b>$original</b> <br />	

	


	<form action="" method="post">
	<fieldset><br />

	<table>

	<tr>
	<td><div class="p2">New Value: &nbsp;</div></td>	


<td><select name="level" size="1">								
	<option>None</option>
	<option>Novice</option>
        <option>Intermediate</option>
        <option>Expert</option>
     </select>
</td>
</tr>	


<tr>
<td colspan="2">&nbsp;</td>
</tr>

<tr>
<td><input type="submit" name="submit" style="background-color: #F3F3F3;" value=" Confirm Change " /></td> 
<td><input type="button" style="background-color: #F3F3F3;" value=" Back to Profile " onclick="window.location.href='admin_editprofile.php?id=$_GET[id]&name=$username'" /></td> 
</tr>

</table>

</form>

</p>";	

}
}








if($_GET[field] <> "level" && $_GET[field] <> "location")
{ 
 	$field = $_GET[field];


	if(isset($_POST['submit']))
 	  { 
	 	if (isset($_POST[$field]))
		 {
		  $new = $_POST[$field];

			if ($new == $original)
			 {
			  $new = FALSE;
			  echo "<p><font color="red">Please enter a new value (they currently match) or click CANCEL</font></p>";
			 }
		 }



		function language_filter($string)
		 { 
		  // define the bad words. 
   		  $obscenities = array("sw3ar","w0rds","g0","h3r3", "<span style='color:blue' title='I&#39;m naughty, are you naughty?'>smurf</span>", "arse", "cunt", "<span style='color:blue' title='I&#39;m naughty, are you naughty?'>smurf</span>", "bugger", "<span style='color:blue' title='I&#39;m naughty, are you naughty?'>smurf</span>"); 
   		
                  // for every bad word 
    		  foreach ($obscenities as $curse_word)
                     { 
       		      // see if it exists in the sentence 
        	      if (stristr(trim($string),$curse_word)) 
                         { 
           	          $length = strlen($curse_word); 
           	          for ($i = 1; $i <= $length; $i++) 
                            { 
                             $stars .= "*"; 
            	            } 
           	       
                      // replace the curseword with stars 
           	      $string = eregi_replace($curse_word,$stars,trim($string)); 
           	      $stars = ""; 
       		          } 
    		      }	 
                  // return the words, with bad words starred out 
                  return $string; 
                  } 


			if($field == "email") 	
			{
			// Check for an email address.
			if (eregi ("^[[]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$", stripslashes(trim($_POST[$field])))) {
			$new = escape_data($_POST[$field]);
			} else {
			$new = FALSE;
			echo '<p><font color="red">Please enter a valid email address!</font></p>';
			}
			}



			if($field == "first_name") 	
			{
			// Check for a first name.
			if (eregi ("^[[].' -]{2,15}$", stripslashes(trim($_POST[$field])))) {
			$new = escape_data($_POST[$field]);
			} else {
			$new = FALSE;
			echo '<p><font color="red">Please enter a valid first name! (letters only)</font></p>';
			}
			}



			if($field == "last_name") 	
			{
			// Check for a last name.
			if (eregi ("^[[].' -]{2,30}$", stripslashes(trim($_POST[$field])))) {
			$new = escape_data($_POST[$field]);
			} else {
			$new = FALSE;
			echo '<p><font color="red">Please enter a valid last name! (letters only)</font></p>';
			}
			}



			if($field == "age") 	
			{	
			// Check for an age.
			if (!isset($_POST[$field]) || (!is_numeric($_POST[$field]) || (strlen($_POST[$field]) < 2) || (strlen($_POST[$field]) > 3)))
	 		{
	  		$new = FALSE;
	 		echo '<p><font color="red">Please enter your age! (numbers only - 3 max)</font></p>';		
	 		}
         		else  
         		{
	  		$new = $_POST[$field];	
	 		}
			}



			if($field == "occupation") 	
			{
			// Check for an occupation.
			if (eregi ("^[[].' -]{2,30}$", stripslashes(trim($_POST[$field])))) {
			$new = language_filter($_POST[$field]);
			} else {
			$new = FALSE;
			echo '<p><font color="red">Please enter your occupation! (letters only)</font></p>';
			}
			}



			if($field == "hobbies") 	
			{
			//  Check for hobbies
			if (strlen($_POST[$field]) >0) 
			{
			$new = language_filter($_POST[$field]);
			} else
			{
			$new = "Unspecified";
			}
			}



	
			if($field == "icq") 	
			{
			//  Check ICQ number
			if (strlen($_POST[$field]) >0) 
			{
			if (!is_numeric($_POST[$field])) {
			$new = FALSE;
			echo '<p><font color="red">Your ICQ number is invalid</font></p>';
			} else {
			$new = $_POST[$field];
			}
			} else
			{
			 $new = "Unspecified";
			}
			}



			if($field == "aim") 	
			{	
			//  Check for AIM
			if (strlen($_POST[$field]) >0) 
			{
			 $new = $_POST[$field];
			} else
			{
	 		 $new = "Unspecified";
			}
			}
	


			if($field == "msn") 	
			{
			//  Check for MSN
			if (strlen($_POST[$field]) >0) 
			{
			 $new = $_POST[$field];
			} else
			{
			 $new = "Unspecified";
			}
			}


			
			if($field == "website") 	
			{
			//  Check for a valid website if entered
			if (strlen($_POST[$field]) >0) 
			{
           		   if (!preg_match ("/http:\/\/(.*)\.(.*)/i", $_POST[$field])) 
            		     {
	     		      $new = FALSE;
              		      echo '<p><font color="red">Please enter a valid URL for your website</font></p>';	
             		     }
	     		      else
	    		     {
	      		      $new = $_POST[$field];
	    		     } 
		        }
                         else
	                {
	                 $new = "Unspecified";
	                }
			}
         



		 if ($new)
		  {
		   $query = "UPDATE users SET $field='$new' WHERE user_id=$_GET[id]";
		   $result = @mysql_query ($query); // Run the query.
		 

		   if (mysql_affected_rows() == 1) { // If it ran OK.
			{
			 $original = $new;
			}

		   mysql_close(); // Close the database connection.
		
		  }
	           else
		  {
		  echo "<p><font color="red">Please select a different value or click CANCEL to go back</font></p>";
		  }

            }
}


	 echo "<h3>Change Your $field</h3>

	<h5>You can change the registered <b>$field</b> for user $username (ID number $_GET[id]) on this page.</h5>

	<p>
	Enter a new value in the box below, or click CANCEL to go back to the profile<br /><br /><br /><br />

	The current value in the database is: <b>$original</b> <br />	

	


	<form action="" method="post">
	<fieldset><br />

	<table>

	<tr>
	<td><div class="p2">New Value: &nbsp;</div></td>	


<td><input type="text" value="$original" name="$field" size="30" maxlength="50" /></td>
</tr>	


<tr>
<td colspan="2">&nbsp;</td>
</tr>

<tr>
<td><input type="submit" name="submit" style="background-color: #F3F3F3;" value=" Confirm Change " /></td> 
<td><input type="button" style="background-color: #F3F3F3;" value=" Back to Profile " onclick="window.location.href='admin_editprofile.php?id=$_GET[id]&name=$username'" /></td> 
</tr>

</table>

</form>

</p>";	

}

include_once ('includes/footer.html'); // Use the HTML footer file.


?>

Hope that helps![/php_man]

Posted: Thu Oct 28, 2004 10:38 am
by Wayne
what does mysql_connect.php look like?

Posted: Thu Oct 28, 2004 10:40 am
by grahamd
Here's mysqlconnect....

Code: Select all

<?php # User Login Attempt Numero Uno - mysql_connect.php


//   Et voila....the database access info. I'll also create a connection to MySQL and select the database here


//   Setting the database access info as constants...

define('DB_USER', 'graham');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'loginsystem');


if ($dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD)) 

  { // Make the connection

	if (!mysql_select_db (DB_NAME))       
     
              { // If the database can't be selected

		// Handle the error
		my_error_handler (mysql_errno(), 'Could not select the database: ' . mysql_error());
		
		// Print a message to the user, include the footer, and kill the script
		echo '<p>Site currently buggered. Try later.</p>';
            include_once ('includes/footer.html');
		exit();
        
               }  // End of mysql_select_db IF
   } 

else

   {  // If it couldn't connect to MySQL....

		// Print a message to the user including the footer and kill the script here
		my_error_handler (mysql_errno(), 'Could not connect to the database: ' . mysql_error());
		echo '<p>Site currently buggered. Try later.</p>';
		include_once ('includes/footer.html');
		exit();

   } // End of $dbc IF



//	This is a function for escaping and trimming form data...

function escape_data ($data) 
{
 global $dbc;
    
     if (ini_get('magic_quotes_gpc')) 
	{
	 $data = stripslashes($data);
	}
 return mysql_real_escape_string (trim ($data), $dbc);

} // End of escape_data() function

?>

Posted: Thu Oct 28, 2004 10:53 am
by pickle
Well, you should probably make your error statements a little clearer. There is a difference between not being able to connect to mysql and not being able to select a database. Could you show us the exact page that is output? As it is, there's no place that outputs "No Database Selected".

Posted: Thu Oct 28, 2004 10:59 am
by patrikG
pickle wrote:Could you show us the exact page that is output? As it is, there's no place that outputs "No Database Selected".
"No Database Selected" is a standard MySQL error, and is returned by mysql_error().

Posted: Thu Oct 28, 2004 11:20 am
by grahamd
I can't really show you where it appears exactly without screendumps/whatever. It appears in the right-hand menu which is created by my 'footer.html' file. That leads me to suspect the problem lies therein. Here's the footer page....

Code: Select all

</div>

<div id="Menu">

<?php # User Login Attempt Numero Uno - footer.html

//   This page ends the HTML header for the site


/*   Now I want to display links based on the user's login status at this time. If they ain't logged in they'll see the latter half of the following IF statement's jazz....register, login and forgotten password....and if they are logged in and this isn't the logout page they'll see all the user facility links....logout and change password */

if (isset($_SESSION&#1111;'user_id']) AND (substr($_SERVER&#1111;'PHP_SELF'], -10) !='logout.php'))
	&#123;
	 echo '<p><br /><a href="index2.php">Home</a><br />
	       <a href="logout.php">Logout</a><br />
               <a href="change_password.php">Change Password</a><br />
	       <a href="editprofile.php">Edit Your Profile</a><br />
	       <a href="forum.php">Forum</a></p><br />';
        &#125;
else
        &#123; 
         echo '<p><br /><a href="index.php">Home</a><br />
               <a href="register.php">Register</a><br />
               <a href="login.php">Login</a><br />
               <a href="forgot_password.php">Forgotten Password</a></p><br />';
        &#125;

?>

<hr size='1' noshade />

<?php
$limit_time = time() - 300; // 5 Minute time out. 60 * 5 = 300 
$sql = mysql_query("SELECT * FROM ppl_online WHERE UNIX_TIMESTAMP(activity) >= $limit_time AND member='n' GROUP BY ip_address") or die (mysql_error()); 
$sql_member = mysql_query("SELECT * FROM ppl_online WHERE UNIX_TIMESTAMP(activity) >= $limit_time AND member='y' GROUP BY ip_address") or die (mysql_error()); 
$visits = mysql_num_rows($sql); 
$members = mysql_num_rows($sql_member); 





$sql = "SELECT username, date_format(registration_DATE, '%W %M %eth, %Y at %l:%i%p') FROM users GROUP BY user_id";
$lastuser = @mysql_query($sql); 
$num = mysql_num_rows ($lastuser); 
$row = mysql_fetch_array ($lastuser, MYSQL_NUM);

while($row = mysql_fetch_array($lastuser, MYSQL_NUM)) &#123;
$lastregistered = $row&#1111;0];
$whatever = $row&#1111;1];
&#125;

echo "<img src='images/users.gif' />";
echo "<p>There are currently <b>$visits</b> guests and <b>$members</b> members online right now</p>";
echo "<p>The last registered user was <b>$lastregistered</b>.<br />They registered on <b>$whatever</b><br /><br /><br />The site now has <b>$num</b> registered users</p>";

?>

<hr size="1" noshade />

<img src="images/addedinfo.gif" />

<p>
<?php
$offset = 360*10;
$date = gmdate("dS F Y, G:i", time() + $offset);
echo $date;
?><br /><br /><br />

<?php include("counter.php"); ?>

</p>

<hr size="1" noshade />

<p>
<a href="4dm1n/" title="Administrator Section">admin click here</a></p>

</div>
</body>
</html>


<?php  //  Flushing the buffered output to the browser...

mysql_close();
ob_end_flush();

?>

Posted: Thu Oct 28, 2004 11:36 am
by grahamd
Problem solved! And what a silly one it was....

My 'footer.html' demanded a live database connection to produce info like how many people are currently online. At the end of every conditional I closed the database upon successful data submission to it. This meant the footer could no longer get the data it was requesting and so it fired an error at me! Sorted! :D

Thanks for your help guys - glad to get that one off my shoulders

Posted: Thu Oct 28, 2004 11:51 am
by pickle
patrikG wrote:"No Database Selected" is a standard MySQL error, and is returned by mysql_error().
DOH!
Comic Book Guy wrote:There is no emoticon to express what I am feeling!!
An emoticon with a bat to the head would be nice - for times of realized self-stupidity. Maybe they should recind(sp?) my "master" status.

Posted: Thu Oct 28, 2004 12:53 pm
by grahamd
Oh believe me - if I hit myself over the head with a bat every time I realised I was being stupid I wouldn't have much of a head left :wink:
Why is it that the simplest problems are always the hardest to find? Ach well - onwards and upwards!