Spike Lee
Spike Lee

Reputation: 411

basic php question - connecting to database

i literally just started looking into php, connecting to a remote database and returning data. I have been following a tutorial however when i apply the same code (as on the tutorial), i get

Server error

The website encountered an error while retrieving http://localhost:8888/file.php. It may be down for maintenance or configured incorrectly. Here are some suggestions: Reload this web page later.

This is the script - the database connection is fine, i believe its the retrieval of data that causes the error but have no idea on how to fix it ..

  <?php

   // Database credentials
   $host = "localhost"; 
   $db = "json"; 
   $uid = "json"; 
   $pwd = "json1";

    // Connect to the database server   
    $link = mysql_connect($host, $uid, $pwd) or die("Could not connect");

   //select the json database
   mysql_select_db($db) or die("Could not select database");


// Create an array to hold our results
   $arr = array();
   //Execute the query
   $rs = mysql_query("SELECT id,userid,firstname,lastname,email FROM users");

   // Add the rows to the array 
   while($obj = mysql_fetch_object($rs)) {
   $arr[] = $obj;

?>

Upvotes: 0

Views: 339

Answers (2)

Eskil Mjelva Saatvedt
Eskil Mjelva Saatvedt

Reputation: 547

You could consider to use mysql_fetch_assoc() instead of mysql_fetch_object(). A named array is often easier to handle than a more random object.

Added an display of mysql error.

$link = mysql_connect($host , $uid, $pwd);
if (!$link) {
    echo "Error connection to database. MySQL said: ";
    echo mysql_error();
    exit;
}
if (!mysql_select_db($db)) {
        echo "Couldn't select database.";
}

$rs = mysql_query("SELECT id,userid,firstname,lastname,email FROM users WHERE 1=1");

$users = array();
if ($rs && mysql_num_rows($rs) > 0) {
    while($userRow =  mysql_fetch_assoc($rs)){
        $users[] = $userRow; 

        // Or do what you want with the user data
         $id = $userRow['id'];
         $userId = $userRow['userid'];
         $firstname= $userRow['firstname'];
         $lastname= $userRow['lastname'];
         $email= $userRow['email'];

    }
}

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 401182

At the end of your script, you have this :

// Add the rows to the array 
   while($obj = mysql_fetch_object($rs)) {
   $arr[] = $obj;

?>

You are opening { on the while line ; but never closing it.

Upvotes: 4

Related Questions