Php / MySql Error

Rodrigo Costa
Rodrigo Costa used Ask the Experts™
on
Hi folks, I'm getting an error that I can't seem to make it how to solve it.

What I want it is for it to list all records in a certain database. It should work since I copied from another script that I use that it is currently working... So I messed it up somewhere, but I can't seem to find it...

Any help would be much appreciated.

The error :Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/tvuer925/public_html/CurtaNaUERJ/votacao.php on line 15


Cheers!

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Formulário de Inscrição Categoria Amador</title>

<?php
$msg[0] = "Conexão com o banco falhou!";
$msg[1] = "Não foi possível selecionar o banco de dados!";
$conexao = mysql_pconnect("localhost","username","password");
mysql_select_db("tvuer925_youtube",$conexao) or die($msg[1]);


$queryFestival = "SELECT * FROM tbFestivalMaior ORDER BY id DESC";
$resultadoFestival = mysql_query($queryFestival,$conexao);
$linhaFestival = mysql_fetch_array($resultadoFestival);


?>



<style type="text/css">
body,td,th {
	font-family: Verdana, Geneva, sans-serif;
}
body {
	background-image: url(fundoCurta.jpg);
	background-repeat: repeat;
}
a:link {
	color: #333;
}
a:visited {
	color: #333;
}
a:hover {
	color: #333;
}
a:active {
	color: #333;
}
</style>
<script type="text/javascript">
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function maybeDisableButton() {
            var Pall = document.getElementById("email").value;
            var disableButton = false;
            if (Pall == "") disableButton = true;
            document.forms['newsletter'].elements['SubmitCheck'].disabled = disableButton;
}
function validate(newsletter,email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = document.forms[newsletter].elements[email].value;
   if(reg.test(address) == false) {
      alert('Endereço de Email Inválido, favor digitar um endereço válido.');
      return false;
   }
}
</script>
<script type="text/javascript" src="FancyboxYOUTUBE/jquery-1.2.6.min.js">
</script>
<script type="text/javascript" src="FancyboxYOUTUBE/jquery.pngFix.pack.js">
</script>
<script type="text/javascript" src="FancyboxYOUTUBE/jquery.fancybox-1.0.0.js">
</script>

<script type="text/javascript" src="FancyboxYOUTUBE/swfobject.js"></script>
<link rel="stylesheet" type="text/css" href="FancyboxYOUTUBE/fancy.css"/>

<script type="text/javascript">
$(document).ready(function() {
$("a[@rel*=fancyvideo]").fancybox({
overlayShow: true,
showCloseButton: true,
overlayOpacity: 0.9,
frameWidth:640,
frameHeight:360
});
});
</script>
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-26175414-1']);
  _gaq.push(['_setDomainName', 'tvuerj.com.br']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
</head>
<body>
<table width="85%" border="0" align="center">
    <tr>
      <td>&nbsp;</td>
      <td align="center"><strong>Votação</strong></td>
      <td>&nbsp;</td>
    </tr>
</table>
<form id="form1" name="form1" method="post" action="votar.php">
<table width="85%" border="0" align="center">
<?php
while ($linhaFestival = mysql_fetch_array($resultadoFestival)) { ?>
                                  <tr>	
                                  		<td width="21%">Titulo: <?php echo $linhaFestival['titulo'];?></td>								  
                                        <td width="74%">Sinopse:</td>
                                        <td width="5%">Vote:</td>
                                  </tr>
                                  <tr>
                                    	<td><a href="http://www.youtube.com/embed/<?php echo $linhaFestival['link']; ?>" rel="fancyvideo"><img src="http://i1.ytimg.com/vi/<?php echo $linhaFestival['link']; ?>/default.jpg" alt="" width="108" height="81" border="0" /></a></p></td>
                                        <td valign="top"><?php echo $linhaFestival['sinopse'];?></td>
                                        <td><input type="radioId" name="radioId" id="radioId" value=<?php echo $linhaFestival['id'];?> /></td>
                                  </tr>
                                  <tr>
                                      <td>Autor:</td>
                                      <td><?php echo $linhaFestival['autor'];?></td>
                                      <td></td>
                                  </tr>
                                  <tr>
                                      <td>Equipamentos:</td>
                                      <td><?php echo $linhaFestival['equipamentos'];?></td>
                                      <td>Teste de LINK: <?php $linhaFestival['link'];?></td>
                                  </tr>
<?php
}
?>
                </table>
  <p>&nbsp;</p>
</form>
</body>
</html>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
The code seems correct, the only tip I could offer is to check if mysql_select_db succeeds,
it should return true on success, if it fails then maybe you supplied wrong database name or the user you put into mysql_pconnect() does't have select privileges on the db.

try

<?php
$msg[0] = "Conexão com o banco falhou!";
$msg[1] = "Não foi possível selecionar o banco de dados!";
$conexao = mysql_pconnect("localhost","username","password");
$dbtemp = mysql_select_db("tvuer925_youtube",$conexao) or die($msg[1]);
echo "$dbtemp<br/>";

$queryFestival = "SELECT * FROM tbFestivalMaior ORDER BY id DESC";
$resultadoFestival = mysql_query($queryFestival,$conexao);
$linhaFestival = mysql_fetch_array($resultadoFestival);


?>

Open in new window

Sudaraka WijesingheWeb Application Programmer

Commented:
It's possible that executing your query is failing for some reason and mysql_query is returning FALSE instead of the query result resource id. Try the following.
$linhaFestival = array();
$resultadoFestival = mysql_query($queryFestival,$conexao);
if(FALSE === $resultadoFestival) echo mysql_error($conexao);
else $linhaFestival = mysql_fetch_array($resultadoFestival);

Open in new window

Commented:
You should carry out an all stage error trapping to  find out whats failing.
$conexao = mysql_pconnect("localhost","username","password");
if (is_resource($conexao) && stristr($conexao, “mysql”))
{
    mysql_select_db("tvuer925_youtube",$conexao) or die($msg[1]);
    $queryFestival = "SELECT * FROM tbFestivalMaior ORDER BY id DESC";
    $resultadoFestival = mysql_query($queryFestival,$conexao);
      if ($resultadoFestival===FALSE)
          {
            die( 'Query failed');
              }
              
$linhaFestival = mysql_fetch_array($resultadoFestival);
}
ELSE
      die('something wrong with database connection details provided');
Most Valuable Expert 2011
Top Expert 2016
Commented:
supplied argument is not a valid MySQL result resource
This almost always means that the query failed.  Here is a script that shows some of the basics of PHP and MySQL.  Have a look at the error checking.  If you use something like that, it may show you the issues in a way that is easy to read and understand.
<?php // RAY_mysql_example.php
error_reporting(E_ALL);


// THE ABSOLUTE MINIMUM YOU MUST UNDERSTAND TO USE PHP AND MYSQL
// MAN PAGE: http://php.net/manual/en/ref.mysql.php
// MAN PAGE: http://php.net/manual/en/mysql.installation.php
// MAN PAGE: http://php.net/manual/en/function.mysql-connect.php
// MAN PAGE: http://php.net/manual/en/function.mysql-select-db.php
// MAN PAGE: http://php.net/manual/en/function.mysql-real-escape-string.php
// MAN PAGE: http://php.net/manual/en/function.mysql-query.php
// MAN PAGE: http://php.net/manual/en/function.mysql-errno.php
// MAN PAGE: http://php.net/manual/en/function.mysql-error.php
// MAN PAGE: http://php.net/manual/en/function.mysql-num-rows.php
// MAN PAGE: http://php.net/manual/en/function.mysql-fetch-assoc.php
// MAN PAGE: http://php.net/manual/en/function.mysql-fetch-array.php
// MAN PAGE: http://php.net/manual/en/function.mysql-insert-id.php



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


// OPEN A CONNECTION TO THE DATA BASE SERVER
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $err = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $err <br/>";
}

// SELECT THE MYSQL DATA BASE
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
    $err = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $err <br/>";
    die('NO DATA BASE');
}
// IF THE SCRIPT GETS THIS FAR IT CAN DO QUERIES




// ESCAPE ALL DATA FIELDS BEFORE USE IN MYSQL QUERIES
$safe_username = mysql_real_escape_string($_POST["username"]);




// CREATE AND SEND A SELECT QUERY AND TEST THE RESULTS
$sql = "SELECT id FROM my_table WHERE username='$safe_username'";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, SHOW THE ERROR
if (!$res)
{
    $err = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/> $sql <br/>";
    die($err);
}
// 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
$num = mysql_num_rows($res);
$fmt = number_format($num);
if (!$num)
{
    echo "<br/>QUERY FOUND NO DATA: ";
    echo "<br/> $sql <br/>";
}
else
{
    echo "<br/>QUERY FOUND $fmt ROWS OF DATA ";
    echo "<br/> $sql <br/>";
}




// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
while ($row = mysql_fetch_assoc($res))
{
    // ROW BY ROW PROCESSING IS DONE HERE
    var_dump($row);
}




// ANOTHER WAY OF DETERMINING HOW MANY ROWS WE HAVE IN A TABLE
$sql = "SELECT COUNT(*) FROM my_table";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
    $err = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/>$sql <br/>";
    die($err);
}
// 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];
$fmt = number_format($num);
echo "<br/>THERE ARE $fmt ROWS IN THE TABLE";




// 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)
{
    $err = mysql_errno() . ' ' . mysql_error();
    echo "<br/>QUERY FAIL: ";
    echo "<br/> $sql <br/>";
    die($err);
}

// GET THE AUTO_INCREMENT ID OF THE RECORD JUST INSERTED - PER THE DB CONNECTION
$id  = mysql_insert_id($db_connection);
echo "<br/>YOU JUST INSERTED A RECORD WITH AUTO_INCREMENT ID = $id";

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
Sidebar note... Even though MySQL queries are not case-sensitive in their SELECT matching, I believe that the names of tables and columns may be case-sensitive.  I know that in PHP the names of variables (but not classes or functions) are case-sensitive.  You might check for capitalization.

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