Jump to content

Simple array select and echo


unreel

Recommended Posts

I'm working on a simple script to select a set of records from my database and print them on the page... For some reason, this is turning out to be harder for me than I had expected. Could anyone tell me what Im doing wrong?.. Here is my code:

 

<?
// database information 
   $host = 'myHost';       
   $user = 'myUsername'; 
   $password = 'myPassword; 
   $dbName = 'myDbname'; 

   // connect and select the database 
   $conn = mysql_connect($host, $user, $password) or die(mysql_error()); 
   $db = mysql_select_db($dbName, $conn) or die(mysql_error()); 
   
$query = "SELECT * FROM users";  
$result = mysql_query($query); 
$numrows = mysql_num_rows($result); 
while($row = mysql_fetch_array($result)){ 
    echo "You have $numrows user(s) in the database"; 
    echo "First Name: $row[first_name]"; 
    echo "Last Name: $row[last_name]"; 
    echo "Email: $row[email]"; 
} 
?>  

 

When I load my page, it comes up completely blank as if I have no records in the database, but there are 56 records in my database under the users table.

 

Thanks for any help,

Brandon

Link to comment
https://forums.phpfreaks.com/topic/86695-simple-array-select-and-echo/
Share on other sites

Put in some error checking. Also move the "you have" line outside the while loop:

<?php
// database information 
   $host = 'myHost';       
   $user = 'myUsername'; 
   $password = 'myPassword'; 
   $dbName = 'myDbname'; 

   // connect and select the database 
   $conn = mysql_connect($host, $user, $password) or die(mysql_error()); 
   $db = mysql_select_db($dbName, $conn) or die(mysql_error()); 
   
$query = "SELECT * FROM users";  
$result = mysql_query($query) or die("Problem with query: $query<br>". mysql_error()); 
echo 'You have ' . mysql_num_rows($result) . ' user(s) in the database<br>'; 
$numrows = mysql_num_rows($result); 
while($row = mysql_fetch_array($result)){ 
    echo 'First Name: ' . $row['first_name'] . ' '; 
    echo 'Last Name: ' . $row['last_name'] . ' '; 
    echo 'Email: ' . $row['email'] . '<br>'; 
} 
?>

 

Ken

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.