Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Database not selected error

Status
Not open for further replies.

ashstampede

Programmer
Aug 30, 2004
104
GB
I have a weird problem with my php page, I have three or so functions that call the database. two of the functions run and on the third I have output if an error occurred with the database. stating "No database selected"

Code:
 <?php
session_start();
 //redirect the user if they are not admin
 if($_SESSION['user_level'] != 1 || !isset($_SESSION['user_id'])  )
 {
	//get out of here
	//redirect to the page they need to goto
	$url = '[URL unfurl="true"]http://';[/URL] 
	$url.= $_SERVER['HTTP_HOST'];
	//check for trailing slashes
	if((substr($url, -1) =='/') || (substr($url,-1)=='\\'))
	{

		$url = substr($url,0,-1); //chop off the slashes
	}//end check for slashes
			
		$url .= 'login.php';
		header("Location:". $url);
		exit(); // quit the script
 }//not admin or logged in
 
 /**********************************
  Generate the category list
 **********************************/
 function selectList()
{
   require_once('../connection_string.php');
   $selout = "<select name=\"up_category\">\n";
   $query = "SELECT * FROM category";
   $result = @mysql_query($query) OR die("ERROR: " . mysql_error());

   if($result)
   {
     while($row = mysql_fetch_array($result,MYSQL_NUM)) //returns a record if successful
     {
	  $selout .= "<option value=\"$row[0]\">$row[1]</option>\n";
     }
   }
    $selout .="</select>";
    mysql_close();
    echo($selout);
}//end function selectList

# grab the article id from the url address bar
# fecth all the information from the database
# output it to html for display
function populate($id)
{
	require_once('../connection_string.php');
	$query = "SELECT * FROM article WHERE article_id =$id";
	//Select the database
	$result = @mysql_query($query) OR die('ERROR: ' . mysql_error());
	$row = mysql_fetch_array($result);
	$output = "";
	if($row)
	{
	 $output = "<input name=\"up_title\" size=\"45\" maxlength=\"150\" type=\"text\" value=\"";
	 $output .= $row['article_title'] ."\" />\n</p>";
	 $output .= "<p>\nDescription:<br /><textarea name=\"up_desc\" cols=\"45\" rows=\"3\" >";
	 $output .=$row['article_desc'];
	 $output .="</textarea>\n</p><p>\nPost:<br /><textarea name=\"up_body\" cols=\"55\" rows=\"19\" >";
	 $output .=	$row['article_body'];
	}
    mysql_close();
    echo($output);
}//end function
 
/*********************************************************** 
 UPDATE STATEMENT, takes an article id and updates the 
 article where the articale id is equals
**********************************************************/
if(isset($_POST['submitted']))
{
    require_once('../connection_string.php');
    $errors = array();
    //check if all the form entered is empty
    //is title blank?
	if(empty($_POST['up_artId']))
	{
		$errors[] = 'no article ID supplied';
	}
	else
	{
		$artId = escape_data($_POST['up_artId']);
	}
	
    if(empty($_POST['up_title']))
    {
      $errors[] = 'please enter a title';
    }
    else
    {
       $title = escape_data($_POST['up_title']);
    }
     
    //is description blank
    if(empty($_POST['up_desc']))
    {
       $errors[] = 'please enter a description';
    }
    else
    {
       $desc = escape_data($_POST['up_desc']);
    }
	
    //is category empty
    if(empty($_POST['up_category']))
    {
      $errors[] = 'please enter a category';
    }
    else
    {
      $cat = escape_data($_POST['up_category']);
    }
	
    //check if article is empty
    if(empty($_POST['up_body']))
    {
      $errors[] = 'please enter an article body';
    }
    else
    {
      $body = escape_data($_POST['up_body']);
	  $body .= "\n\nEDITED ON: " .date("Y,n,j,H:i:s");
    }
	
	 //is category empty
    if(empty($_POST['up_action']))
    {
      $errors[] = 'please enter a category';
    }
    else
    {
      $action = escape_data($_POST['up_action']);
    }
		
    //if there was no errors proceed
    if(empty($errors))
    {
      
	  if($action=="update")
	  {
		  //insert data into artical table and current table
		  $query ="UPDATE article SET id_cat_art=$cat, article_title ='$title',article_desc= '$desc',article_date = NOW(),article_body = '$body' WHERE article_id =$artID";

		  //send to the database
		  $result = @mysql_query($query) OR DIE('MYSQL ERROR OCCURED' .mysql_error());
	  
		  //mysql affected rows is called for statements that alter the table
		  //returns 0 when a delete occurs,-1 for a fail mysql query, and the 
		  //total number of rows effected by a INSERT and only the rows UPDATED
		  $row = mysql_affected_rows(); //return a record, if execution occured
		  if($row > 0)
		  {
	
			  //redirect to the page they need to goto
			  $url = '[URL unfurl="true"]http://';[/URL] 
			  $url.= $_SERVER['HTTP_HOST'];
			  //check for trailing slashes
			  if((substr($url, -1) =='/') || (substr($url,-1)=='\\'))
			  {
				  $url = substr($url,0,-1); //chop off the slashes
			  }//end check for slashes
				
			  $url .= "../index.php";
	
			  header("Location:" .$url);
			  mysql_close();
			  exit();		
	      }//if returned rows
	  }//if action was update
	  if($action=="delete")
	  {
		  //insert data into artical table and current table
		  $query ="DELETE FROM article WHERE article_id ='$artID'";

		  //send to the database
		  $result = @mysql_query($query) OR DIE('MYSQL ERROR OCCURED' .mysql_error());
	  
		  //mysql affected rows is called for statements that alter the table
		  //returns 0 when a delete occurs,-1 for a fail mysql query, and the 
		  //total number of rows effected by a INSERT and only the rows UPDATED
		  $row = mysql_affected_rows(); //return a record, if execution occured
		  if($row > 0)
		  {
	
			  //redirect to the page they need to goto
			  $url = '[URL unfurl="true"]http://';[/URL] 
			  $url.= $_SERVER['HTTP_HOST'];
			  //check for trailing slashes
			  if((substr($url, -1) =='/') || (substr($url,-1)=='\\'))
			  {
				  $url = substr($url,0,-1); //chop off the slashes
			  }//end check for slashes
				
			  $url .= "../index.php";
	
			  header("Location:" .$url);
			  mysql_close();
			  exit();		
	      }//if returned rows
		  
	  }
    }//end if empty errors
    else
    {
	  $errors[] = "an error occured in the database";
      //no records found
	  $errors[] = mysql_error() ."<br /><br />Query: " .$query;
     }
			
    //close the database connection
	mysql_close();
}//form has been posted
else
{
  $errors = NULL;
}
?>
</head>


 <div id="content">
 	<div id="post">
	<form action="update.php" method="post" name="updater">
		<p>
			Article Id:<br />
			<input type="text" name="up_artId" value="<?php echo $_GET['id'];?>" />
		</p>
		 <p>
	 		Category:<br />
			<?php 
				selectList();
			?>
       	</p>
		<p>
			Title:<br />
			<?php
				$id = $_GET['id'];
				populate($id);
			?>
			</textarea>

basically what goes wrong is when the article id is sent in the url header from another page, the code doesn't successfully connect to th databse to retrieve the data.
 
It would be very helpful if you'd povirde the line number on which the error is reported and to point it out in the code.
It's just too much code and too little time...

How is the article id sent in the URL header?
 
does connection_string contain:

mysql_select_db(dbname);

?

______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
DRJ478: the error doesn't happen on any line persay, the error i get is the mysql. but the function that is called that doesn't finish is 'populate', but before calling populate i call a function selectlist, that goes to the same database but different table, and the code work fine until populate is called.

I assume it is the OR die statement after the select is called.


Code:
 function populate($id)
{
    require_once('../connection_string.php');
    $query = "SELECT * FROM article WHERE article_id =$id";
    //Select the database
    $result = @mysql_query($query) OR die('ERROR: ' . mysql_error());
    $row = mysql_fetch_array($result);
    $output = "";
    if($row)
    {
     $output = "<input name=\"up_title\" size=\"45\" maxlength=\"150\" type=\"text\" value=\"";
     $output .= $row['article_title'] ."\" />\n</p>";
     $output .= "<p>\nDescription:<br /><textarea name=\"up_desc\" cols=\"45\" rows=\"3\" >";
     $output .=$row['article_desc'];
     $output .="</textarea>\n</p><p>\nPost:<br /><textarea name=\"up_body\" cols=\"55\" rows=\"19\" >";
     $output .=    $row['article_body'];
    }
    mysql_close();
    echo($output);
}//end function

KarveR: this is the line in my connection string file, so yes i do call the database name.
Code:
 //Select the database
	@mysql_select_db (DB_NAME) OR die('Could not select the database: ' .mysql_error());
 
the error doesn't happen on any line persay...
It must be a specific query that triggers the error and the query is issued via PHP code on a specific line.
My recommendation is to add specific indication where the error is triggered from, e.g. adding the line number by using
Code:
@mysql_query($sql) or die('Error: '.__FILE__.__LINE__.' '.mysql_error().' '.$sql);

I would also print out the query itself to see what's in there. That would give more information as to track down what's happening.
The code itself appears clean.
 
I'd remove the @ symbols and make mysql barf whatever error its trying to show.

______________________________________________________________________
There's no present like the time, they say. - Henry's Cat.
 
i think the problem is that you are calling mysql_close() in some places (eg where $row=0). in such a case you need to reopen a connection to the datbase before you can perform a query.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top