Reputation: 1
I get the following error when i try to display index.php Warning: mysql_numrows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\cards\index.php on line 18
I can't tell if I'm not connecting to the database correctly or if thre is some other error. Basically I'm trying to display 3 random lines of data from my table "cards". The column in the table that I want to display the data from is "playerName". I'm not worried about formatting the data yet. Code is below:
<?php
include_once 'header.php';
require_once 'config.php';
$con = mysql_pconnect("localhost","*****","*****");
mysql_select_db("USE cards",$con);
$cards=0;
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT * FROM cards ORDER BY RAND() LIMIT 3";
$results = mysql_query($sql);
$array = mysql_fetch_array($results);
$num=mysql_num_rows($results);
$i=0;
while ($i < $num) {
echo $rows['playerName'];
$i++;
}
include_once 'footer.php';
?>
I know this is probably a simple newbie question, but I appreciate the help.
Upvotes: 0
Views: 92
Reputation: 2170
Two things, echoing an array wont print it(echo $results;) instead use print_r($results) or var_dump($results) and the other thing, I reckon the error is caused be cause no results are returned, but if you use var_dump or print_r you will be able to verify whether that is the case :)
also there is a typo here: $con = mysql_pconnect("localhost","jalexander","brunswick3"); remove the p from connect :)
Also, you might want to replace your db credentials with asterixes on here :)
Finally, you declare the variable cards but never use it?
In fact one more, change $rows[playerName] to $rows['playerName']
To get different rows instead of using a while loop you can use a foreach like so:
foreach($array as $row){
echo $row['playerName'];
}
Or to do it using a while loop use
$i=0;
while ($i < $num) {
echo $rows[$i]['playerName'];
$i++;
}
It did not work in your current code because you was not looping through the elements of the array, just echoing the same one each time
Upvotes: 1
Reputation: 5239
Also, it's mysql_num_rows (not mysql_numrows).
Manual: http://php.net/manual/en/function.mysql-num-rows.php
Upvotes: 1
Reputation: 1087
Your mysql_select_db call should take only the database name as first argument, not the entire USE statement. Most likely it silently fails and does not select the cards database. Then the query fails (again, silently) returning false.
Upvotes: 3