MySql Query on HTML page

JackoPinto
JackoPinto used Ask the Experts™
on
Hi.

I'm a complete newbie here, just started to get into the whole php mysql deal.

I have a database set up, with data on it and I'm trying to display this data inside an html page.  I thought I had set up everything correctly but it just doesn't work!

At the top of my HTML page I have the following code to connect to the database and such:

 <?php
include 'config.php';
include 'opendb.php'; ?>

I checked the connect info on the config file and looks all right.

Here's the query I'm trying to run at the middle of the page:

  <?php  
mysql_query("SET NAMES 'charset=CP1251' ");
$query = "SELECT * FROM `ap_form_14` ORDER BY ID DESC LIMIT 3";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{

echo " <div id=\"Activleftcolumn\"><img width='167px;' height='217px;' style='border:dotted 1px #cccccc; padding: 3px;' src='/forms/imagesforms/form_14/files/" . $row["element_1"] . "' /></div>";
echo "<div id=\"Actirightcolumn\">
<div id=\"actidate\">" . $row["element_3"]. "</div>
<div id=\"actihora\">
<span>De " . $row["element_4"]. "</span>
<span> A " . $row["element_7"]. "</span>
</div>
<div id=\"actititle\">" . $row["element_2"]. "</div>
<div id=\"actides\">" . $row["element_6"]. "</div>
<div id=\"actireserv\">" . $row["element_5"]. "</div>

</div>";

}
 

?>




At the bottom I have: <?php
include 'closedb.php';
?>

I upload the page to the server and nothing comes up.  I have other php code on that same page which is working fine.

I've tried a million things and I don't know what else to do! Again, I'm a complete novice. Please help I really need to move ahead with this!

Here's the link to that page:  http://www.libreriafrancesa.net/nuevo.php

Any more info I need to provide? Do you need me to past the full code? Thanks for your help! Desperate here.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
You can add mysql_error(); to have the status of the last command printed.
I'd recommend adding those after each mysql_query() call.

Author

Commented:
Thanks.

But where would I add that inside my code?

Commented:
mysql_query will return FALSE if it had any problems executing query.  You have to check for this and if it did return FALSE, then you can use mysql_error() to learn why.  Something like this should work

$result = mysql_query($query);
if( $result === FALSE ) {
  print( 'Invalid query: ' . mysql_error());
} else {
while($row = mysql_fetch_array($result))
...
}

for more information: http://us3.php.net/manual/en/function.mysql-query.php

Author

Commented:
Thank you but I don't know how to place that in my code.  I tried a couple of things but it didn't work.

This is the main query:

<?php  
mysql_query("SET NAMES 'charset=CP1251' ");mysql_error();
$query = "SELECT * FROM `ap_form_14` ORDER BY ID DESC LIMIT 2";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{

echo " <div id=\"Activleftcolumn\"><img width='167px;' height='217px;' style='border:dotted 1px #cccccc; padding: 3px;' src='/forms/imagesforms/form_14/files/" . $row["element_1"] . "' /></div>";
echo "<div id=\"Actirightcolumn\">
<div id=\"actidate\">" . $row["element_3"]. "</div>
<div id=\"actihora\">
<span>De " . $row["element_4"]. "</span>
<span> A " . $row["element_7"]. "</span>
</div>
<div id=\"actititle\">" . $row["element_2"]. "</div>
<div id=\"actides\">" . $row["element_6"]. "</div>
<div id=\"actireserv\">" . $row["element_5"]. "</div>

</div>";




}
 

 

?>


Where would that go?

Please keep in mind that I have very little, if any, with all this.

I

Commented:

<?php  
mysql_query("SET NAMES 'charset=CP1251' ");mysql_error();
$query = "SELECT * FROM `ap_form_14` ORDER BY ID DESC LIMIT 2";
$result = mysql_query($query);
if( $result === FALSE ) {
  echo '<div class="ERROR">'.mysql_error().'</div>';
} else {
while($row = mysql_fetch_array($result))
{

echo " <div id=\"Activleftcolumn\"><img width='167px;' height='217px;' style='border:dotted 1px #cccccc; padding: 3px;' src='/forms/imagesforms/form_14/files/" . $row["element_1"] . "' /></div>";
echo "<div id=\"Actirightcolumn\">
<div id=\"actidate\">" . $row["element_3"]. "</div> 
<div id=\"actihora\">
<span>De " . $row["element_4"]. "</span>
<span> A " . $row["element_7"]. "</span>
</div>
<div id=\"actititle\">" . $row["element_2"]. "</div>
<div id=\"actides\">" . $row["element_6"]. "</div>
<div id=\"actireserv\">" . $row["element_5"]. "</div>

</div>";
} 
}
?>

Open in new window

Author

Commented:
Thank you atchijov, I see the error now.  I believe my two PHP statements are "crashing" with one another.

I have one on top, that calls my menu that states:

<?php
 include 'menu/menu.class.php';
 $menu = new Menu("mainmenu");

?>
<?php
      $menu->makeMenu();
      ?>

The second one, which we're looking at what is posted above.

The error I get is:  Table 'menu.ap_form_14' doesn't exist

The table is called ap_form_14, not menu.ap_form_14.  So I'm guessing it's getting "menu" from that other statement.

How do I correct it so that they don't "interfere" with one another?

The URL is: http://libreriafrancesa.net/nuevo.php

Thanks!
Most Valuable Expert 2011
Top Expert 2016
Commented:
You've got a lot of moving parts there, and we may not be able to completely debug your code.  In the code snippet is my teaching example of how to do some of the basics in PHP and MySQL.   Please read it over carefully - code, comments and especially the man page references.  It may give you some good ideas about how to construct your code and visualize your data.

Add error_reporting(E_ALL) to the top of all your scripts.  You WANT to see all the messages at this point in the development cycle.

Here is a book that will help you to get a foundation in PHP and MySQL.  It is very readable, has a downloadable code library and it has been a part of my professional library since Version One.  Most of the SitePoint books are good, this one is excellent.
http://www.sitepoint.com/books/phpmysql4/

Best of luck with your project, ~Ray
<?php // RAY_mysql_example.php
error_reporting(E_ALL);

// IMPORTANT PAGES FROM THE MANUALS
// MAN PAGE: http://us2.php.net/manual/en/ref.mysql.php
// MAN PAGE: http://us2.php.net/manual/en/mysql.installation.php
// MAN PAGE: http://us.php.net/manual/en/function.mysql-error.php



// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";        // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "??";
$db_word = "??";

// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-connect.php
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>NO DB CONNECTION: ";
   echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>NO DB SELECTION: ";
   echo "<br/> $errmsg <br/>";
   die('NO DATA BASE');
}
// IF WE GOT THIS FAR WE CAN DO QUERIES




// ESCAPING A DATA FIELD FOR USE IN MYSQL QUERIES
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-real-escape-string.php
$safe_username = mysql_real_escape_string($_POST["username"]);




// CREATING AND SENDING A SELECT QUERY AND TESTING THE RESULTS
// MAN PAGE:http://us2.php.net/manual/en/function.mysql-query.php
$sql = "SELECT id FROM my_table WHERE username='$safe_username'";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
// MAN PAGE: http://us.php.net/manual/en/function.mysql-error.php
if (!$res)
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>QUERY FAIL: ";
   echo "<br/>$sql <br/>";
   die($errmsg);
}
// IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESOURCE-ID IN $res SO WE CAN NOW USE $res IN OTHER MYSQL FUNCTIONS




// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-num-rows.php
$num = mysql_num_rows($res);
if (!$num)
{
   echo "<br/>QUERY FOUND NO DATA: ";
   echo "<br/>$sql <br/>";
}
else
{
   echo "<br/>QUERY FOUND $num ROWS OF DATA ";
   echo "<br/>$sql <br/>";
}




// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-fetch-assoc.php
echo "<pre>\n"; // MAKE IT EASY TO READ
while ($row = mysql_fetch_assoc($res))
{
   var_dump($row); // MAN PAGE: http://us2.php.net/manual/en/function.var-dump.php
}




// A WAY OF DETERMINING HOW MANY ROWS WE HAVE IN A TABLE
// MAN PAGE: http://us.php.net/mysql_fetch_array
$sql = "SELECT COUNT(*) FROM my_table";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>QUERY FAIL: ";
   echo "<br/>$sql <br/>";
   die($errmsg);
}
// GET THE RESULTS SET ROW IN AN ARRAY WITH A NUMERIC INDEX - POSITION ZERO IS THE COUNT
$row = mysql_fetch_array($res, MYSQL_NUM);
$num = $row[0];




// MAKING AN INSERT QUERY AND TESTING THE RESULTS
$sql = "INSERT INTO my_table (username) VALUES (\"$safe_username\")";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>QUERY FAIL: ";
   echo "<br/>$sql <br/>";
   die($errmsg);
}
// GET THE AUTO_INCREMENT ID OF THE RECORD JUST INSERTED - PER THE DB CONNECTION
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-insert-id.php
$id  = mysql_insert_id($db_connection);

Open in new window

Commented:
Take a look into PHP files you including at the top of the screen.  One of them (most likely opendb.php) setting up connection to your DB.  You should look for 'mysql_connect'.  Most likely you will see something like this:

$someVarName = mysql_connect( .... )

If you did find line like this, try to change your mysql_query() calls by adding second parameter "$someVarName".

For example if you see line

$foo = mysql_connect( ... )

then you will need to change you mysql_query to

mysql_query(  ..., $foo );
Most Valuable Expert 2011
Top Expert 2016

Commented:
Regarding mysql_connect() - all MySQL queries will use the last connection unless you tell MySQL otherwise.  A more likely cause of error is that the connect or select statement failed and the script did not test for the failure.  Happens a lot when the password is wrong.

Author

Commented:
Thank you for your comments.

I'm including the opendb.php file that's called on top of the page and also the code for the page: http://libreriafrancesa.net/nuevo.php, please have a look at how I have it.


I don't know how to keep things from crashing with one another! If the table is called: ap_form_14, why does the error show: Table 'menu.ap_form_14' doesn't exist.  

Thank you very much for helping me solve this!





<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

 <?php
include 'config.php';
include 'opendb.php'; ?>
<script type="text/javascript" src="slideshow/flashdetect.js"></script>
<link rel="stylesheet" type="text/css" href="nuevo/main.css" />
<link rel="stylesheet" type="text/css" href="menu/css/menu_style.css" media="screen">
<script type="text/javascript" src="'menu/js/jquery.js'"></script>
<script type="text/javascript" src="'meny/js/mrmenu.js'"></script>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<?php
 include 'menu/menu.class.php';
 $menu = new Menu("mainmenu");

?>

			





</head>

<body>

 <!-- Begin Wrapper -->
   <div id="wrapper">
   
   
         <!-- Begin Header -->
         <div id="header"><a title="LibreriaFrancesa.net" href="http://libreriafrancesa.net/"><img style="float: left; border:none;" src='http://libreriafrancesa.net/images/varios/LogoSitio.png' alt="LibreriaFrancesa.net" /></a> </div>
          <div id="header2">
          <div align="center" class="menu">

<?php 
	//This is the actual menu, can be placed anywhere you like!
	$menu->makeMenu(); 
	?>

</div></div>

		 <!-- End Header -->
		 
		 <!-- Begin Left Column -->
		 <div id="leftcolumn">
         
         
         <div>
         
         <div class="cate">
         <div id="categorias">
         CATEGORÍAS
       </div>
        <ul>
									<li>
					<a href="/dev/index.php/shop/Frances-Metodos-y-Diccionarios.8">Francés: Métodos y Diccionarios</a>
		  </li>
									<li>
					<a href="/dev/index.php/shop/Idiomas.9">Idiomas</a>
		  </li>
									<li>
					<a href="/dev/index.php/shop/Jeunesse.10">Jeunesse</a>
		  </li>
									<li>
					<a href="/dev/index.php/shop/Litterature-Francaise.11">Litterature Française</a>
		  </li>
									<li>
					<a href="/dev/index.php/shop/Turismo.12">Turismo</a>
		  </li>
		   </ul>
           </div>
                  
         </div>
         
		 <div align="center" id="bannerleft">
		    
</div>
		 
		 </div>
		 <!-- End Left Column -->
		 
		 <!-- Begin Content Column -->
		 <div id="content">
		 <div style="margin-top:8px" align="center" id="flashcontent">
			<p>Se requiere «Flash Player 6» para funcionamiento de la marquesina. <a href="http://www.macromedia.com/go/getflashplayer" >Click AQUÍ</a> para ir a la página correspondiente y obtenerlo.			</p>
	</div>
		
		<script type="text/javascript">
			var so = new SWFObject("slideshow/slideshow.swf", "gallery", "500", "333", "6", "#ffffff");
			so.write("flashcontent");
		</script>      
	      
		 
          <div>
         
    
       <?php  
mysql_query("SET NAMES 'charset=CP1251' ");mysql_error();
$query = "SELECT * FROM `ap_form_14` ORDER BY ID DESC LIMIT 2";
$result = mysql_query($query);
if( $result === FALSE ) {
  echo '<div class="ERROR">'.mysql_error().'</div>';
} else {
while($row = mysql_fetch_array($result))
{

echo " <div id=\"Activleftcolumn\"><img width='167px;' height='217px;' style='border:dotted 1px #cccccc; padding: 3px;' src='/forms/imagesforms/form_14/files/" . $row["element_1"] . "' /></div>";
echo "<div id=\"Actirightcolumn\">
<div id=\"actidate\">" . $row["element_3"]. "</div> 
<div id=\"actihora\">
<span>De " . $row["element_4"]. "</span>
<span> A " . $row["element_7"]. "</span>
</div>
<div id=\"actititle\">" . $row["element_2"]. "</div>
<div id=\"actides\">" . $row["element_6"]. "</div>
<div id=\"actireserv\">" . $row["element_5"]. "</div>

</div>";
} 
}
?>



         
         
         </div>
         
         <!--- END CONTENT --->
		 </div>
         
         
        
 <!-- End Content Column -->
		 
		 <!-- Begin Right Column -->
		 <div id="rightcolumn">
         
         <div>
  
  </div>
         
         
         
		 <div align="center" id="bannerright">
		    </noscript>
</div>
		   
		 
		 </div>
		 <!-- End Right Column -->
		 
		 <!-- Begin Footer -->
		 <div id="footer">	     </div>
	 <!-- End Footer -->
		 
   </div>
   <!-- End Wrapper -->
   
 


<?php 
include 'closedb.php';
?>
</body>



</html>

Open in new window

opendb.php
Most Valuable Expert 2011
Top Expert 2016

Commented:
"menu" is the name of the data base that contains the table named "ap_form_14"
Commented:
assuming that Menu does not use the same variable ($conn), try to modify your code as following:

mysql_query("SET NAMES 'charset=CP1251' ", $conn );
$query = "SELECT * FROM `ap_form_14` ORDER BY ID DESC LIMIT 2";
$result = mysql_query($query, $conn );

Author

Commented:
Thanks Ray,

That's where I have my problem.

<?php
      $menu->makeMenu(); ?>., calls the menu on the page and the database for that is called menu.


<?php  
mysql_query("SET NAMES 'charset=CP1251' ");mysql_error();
$query = "SELECT * FROM `ap_form_14` ORDER BY ID DESC LIMIT 2";
$result = mysql_query($query);
if( $result === FALSE ) {
  echo '<div class="ERROR">'.mysql_error().'</div>';
} else {
while($row = mysql_fetch_array($result))
{

echo " <div id=\"Activleftcolumn\"><img width='167px;' height='217px;' style='border:dotted 1px #cccccc; padding: 3px;' src='/forms/imagesforms/form_14/files/" . $row["element_1"] . "' /></div>";
echo "<div id=\"Actirightcolumn\">
<div id=\"actidate\">" . $row["element_3"]. "</div>
<div id=\"actihora\">
<span>De " . $row["element_4"]. "</span>
<span> A " . $row["element_7"]. "</span>
</div>
<div id=\"actititle\">" . $row["element_2"]. "</div>
<div id=\"actides\">" . $row["element_6"]. "</div>
<div id=\"actireserv\">" . $row["element_5"]. "</div>

</div>";
}
}
?>, is the query I'm trying to run and the database that contains this data is called forms.




Most Valuable Expert 2011
Top Expert 2016

Commented:
What is the SET NAMES for?  Why do you need to do that?

Can you please post the openDB script in the code snippet?   Thanks.

Author

Commented:
Thanks Ray. I tried to use set names so that the query displays accented characters properly, but it's not actually.

Author

Commented:
Thanks atchijov,

I will try this and I'll get back to you.
Most Valuable Expert 2011
Top Expert 2016

Commented:
How many data bases do you have in this scenario?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial