views:

31

answers:

3
+1  Q: 

mysql error in php

i'm trying to run this php code which should display a quote from mysql, but can't figure out where is it going wrong. the result variable is null or empty. can someone help me out. thanks!

<?php
include 'config.php';

// 'text' is the name of your table that contains
// the information you want to pull from
$rowcount = mysql_query("select count(*) as rows from quotes");

// Gets the total number of items pulled from database.
while ($row = mysql_fetch_assoc($rowcount))
{
$max = $row["rows"];
//print_r ($max);
}

// Selects an item's index at random 
$rand = rand(1,$max)-1;
print_r ($rand);
$result = mysql_query("select * from quotes limit $rand, 1") or die ('Error: '.mysql_error());
if (!$result or mysql_num_rows($result))
{
echo "Empty";
}
else{
while ($row = mysql_fetch_array($result)) {

$randomOutput = $row['cQuotes'];
echo '<p>' . $randomOutput . '</p>';
}
}
+1  A: 
if ($result && mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_array($result)) {
        $randomOutput = $row['cQuotes'];
        echo '<p>' . $randomOutput . '</p>';
    }
} else {
    echo "Empty";
}
Ivo Sabev
thanks! that worked!
fuz3d
+2  A: 
$result = mysql_query("SELECT * FROM quotes ORDER BY rand() LIMIT 1") or die ('Error: '.mysql_error());
if (!$result || mysql_num_rows($result) == 0)
    echo "Empty";
else {
    while ($row = mysql_fetch_array($result)) {
        $randomOutput = $row['cQuotes'];
        echo '<p>' . $randomOutput . '</p>';
    }
}
thetaiko
+1  A: 
// your script probably can't go on without this file?
require 'config.php';

// I prefer to always pass the connection resource to mysql_query/mysql_real_escape_string
// assume $mysql = mysql_connect....
$result = mysql_query("SELECT Count(*) AS rows FROM quotes", $mysql)
  or die(mysql_error());
// there's only one row with only one column, so mysql_result() is fine
$rowcount = mysql_result($result, 0, 0);
$rand = rand(0,$rowcount-1);

$result = mysql_query("SELECT cQuotes FROM quotes LIMIT $rand, 1", $mysql)
  or die ('Error: '.mysql_error());

// there's either one or zero records. Again, no need for a while loop
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
  echo "Empty";
}
else{
  // do you have to treat $row['cQuotes'] with htmlspecialchars()?
  echo '<p>', $row['cQuotes'], '</p>';
}
VolkerK
thank you! this was helpful.
fuz3d