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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

echo duplication and page reload error 1

Status
Not open for further replies.

ashstampede

Programmer
Aug 30, 2004
104
0
0
GB
I am fairley new to php and mysql so my first project I decide to make the ever infamous web blog. I have experience with MS SQL and ASP.net.

At the moment I am having two problems, that I cannot figure out for the life of me. The first is with a function I have created, it is called in the html body of the page, it is a mysql select statement that retrieves all the categories from the database and loops row by row generating a drop down menu for an html form.

The problem is it will show the results twice; the list is generated by order in the database and then repeats itself.

As in the total rows are 52 in the database so there are 104 catergories in the drop downlist. The order in which the catergories are listed are 1- 52 then it repeates itself. However looking at the html code, there is only one copy of the list generated.

My second problem, is after I have posted to the database, adding the new ”post” to the database with an insert, I redirect back to the same page, this time I get a php warning stating:

PHP Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /Applications/MAMP/htdocs/cardboard/add.php on line 57

The page does not load fully at this point and is unusable.

Can someone please shed light on this, its been a thorn in my side for the last 3 days.

Below is the php page in question

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']; 
	$url.= dirname($_SERVER['PHP_SELF']);
	//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
	
if(isset($_POST['submitted']))
{
    require_once('conn.php');//db connection settings
    $errors = array();
    //check if all the form entered is empty
    //is title blank?
    if(empty($_POST['ps_title']))
    {
      $errors[] = 'please enter a title';
    }
    else
    {
       $title = escape_data($_POST['ps_title']);
    }
     
    //is description blank
    if(empty($_POST['ps_title']))
    {
       $errors[] = 'please enter a description';
    }
    else
    {
       $desc = escape_data($_POST['ps_desc']);
    }
    //is category empty
    if(empty($_POST['ps_category']))
    {
      $errors[] = 'please enter a category';
    }
    else
    {
      $cat = escape_data($_POST['ps_category']);
    }
    //check if article is empty
    if(empty($_POST['ps_body']))
    {
      $errors[] = 'please enter an article body';
    }
    else
    {
      $body = escape_data($_POST['ps_body']);
    }
		
    //if there was no errors proceed
    if(empty($errors))
    {     
      //insert data into artical table and current table
      $query ="INSERT INTO article(id_cat_art,article_title,article_desc,article_date,article_body)";
      $query .="VALUES($cat,'$title','$desc',NOW(),'$body');";
      //send to the database
      $result = @mysql_query($query);

/*******************************************************************/

//suspected line of php error line 57
      $row = mysql_fetch_array($result,MYSQL_NUM); //return a record, if execution occured
      if($row)
      {
	
        //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 .= 'add.php';
	 header("Location:". $url);
	 $_POST['submitted'] = NULL;
	 exit();		   
      }
      else
      {
	$errors[] = 'an error occured in the database';
        //no records found
	$errors[] = mysql_error() . '<br /><br />Query: '. $query;
	$_POST['submitted'] = NULL;
      }
			
    }//end if empty errors
   
    //close the database connection
    mysql_close();
}//form has been posted
else
{
  $errors = NULL;
}


function selectList()
{
   require_once('conn.php');
   $errors[] = array(); 	
   $selout = "<select name=\"ps_category\">\n";
   $query = "SELECT * FROM category;";
   $result = @mysql_query($query);
   if(!$result)
   {
     $errors[] = "Query failed";
     exit();
   }
   else
   {
     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
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml"[/URL] lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title></title>
<link rel="stylesheet" type="text/css" href=".main.css" media="screen"/>

</head>

<body>
<div id="shell"><!-- contains the bulk of the pages contents and main layout, absolutly centres the page-->
 <div id="header">
 	<p class="header"><a class="header" href="index.htm">home</a></p>
 </div>
 <div id="nav">
    <div class="title">
    	<p class="title">Links</p>
    </div>
	<div id="links">
	    <ul class="nav">
		<li class="nav"><a href="index.htm" title="Home Page and Latest Articles">Front Page</a></li>
		<li class="nav"><a href="add.php" title="Add a New Post">Make A Post</a></li>
		<li class="nav"><a href="delete.php" title="Delete A Post">Delete A Post</a></li>
		<li class="nav"><a href="update.php" title="Update A Post">Update A Post</a></li>			
		<li class="nav"><a href="logout.php" title="Logout">Logout</a></li>
	    </ul>
	</div>
	<div class="title">
		<p class="title">Archives</p>
	</div>
	<div id="cal"></div>
 </div>
 <div id="content">
 	<div class="post">
	  <form action="add.php" method="post">
	    <p>
		Title:<br />
		<input name="ps_title" size="45" maxlength="150" type="text" />
	    </p>
	    <p>
	 	Category:<br />
		<?php 
		  selectList();
		?>
		
       	    </p>
	    <p>
		Description:<br />
		<textarea name="ps_desc" cols="45" rows="3" ></textarea>
	    </p>
	    <p>
		Post:<br />
		<textarea name="ps_body" cols="55" rows="19" ></textarea>                    
	    </p>
	    <p>
		<input type="submit" name="submit" value="Add" />
		<input type="reset"  name="reset" value="Clear" />
		<input type="hidden" name="submitted" value="TRUE" />
	    </p>
	</form>
	<p class="phpError">
	  <?php
	    if(!empty($errors))
	    {
		foreach($errors as $msg)
		{
		   echo " - $msg<br />\n" ;
		}
	    }
		
	  ?>
		
	 </p>
		
	</div><!-- post -->
 </div><!-- end container -->
 <div id="footer">
 	<p class="footer">
	
	</p>
 </div><!-- end footer -->
 
</div><!-- end shell container -->

</body>
</html>
 
The line 57 error is the easy one. Your script is using mysql_query() to perform an "INSERT INTO" query, then feeding the return of that function into mysql_fetch_array().

Mysql_fetch_array() expects that its first input parameter be a MySQL resource handle. But when you use mysql_query() with an "INSERT INTO" query, you will get back only either boolean TRUE or boolean FALSE, depending on whether the query was successful or not. mysql_query() can return a MySQL resource handle only in the case that it successfully runs a "SELECT", "SHOW", "EXPLAIN" or "DESCRIBE" query. This is documented on the PHP online manual page for mysql_query().


The hard part is the repeated data problem. Unfortunately, I don't know why this is happening, as I only see one place where the selectList() (I assume this is the offending function) function is called, and the invokation does not appear to be in a loop. Just to ask the dumb question, how have you verified that the data is not actually doubled in the database?



Want the best answers? Ask the best questions! TANSTAAFL!
 
sleipnir214, Thanks for the answers but just a follow up.

*well I read the manual of php link you posted and it said to use mysql_affected_rows() for statements that modify the tables.

as for how do i know its not double I ran a select * from the table and it returns just 1 list equaling 52 rows
 
ah yeah it is as the function is called twice, or the output is outputted twice.

function and call to the database
Code:
function selectList()
{
   require_once('conn.php');
   $errors[] = array();     
   $selout = "<select name=\"ps_category\">\n";
   $query = "SELECT * FROM category;";
   $result = @mysql_query($query);
   if(!$result)
   {
     $errors[] = "Query failed";
     exit();
   }
   else
   {
     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

code called
Code:
 <p>
       Category:<br />
       <?php  selectList();  ?>
  </p>
 
Sorry, but I just don't see where the code you posted could be producing the SELECT tag twice.

I even created a database on my system an guessed at the content of conn.php and login.php. I can get the script to run, but not to produce the SELECT twice.

Is is possible the script you're trying to edit is in a copy of the file your web server is running?



Want the best answers? Ask the best questions! TANSTAAFL!
 
ah no It was my database entries, there was orignal 52 rows, but then i changed most of the categories so what must have happen origanally was when i copied and paste the insert staetments over again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top