Help undefined index in php

Help meee, i have an error undefined index: name

here is the code:

     function get_nama(){
        $email  = isset($_SESSION['email']) ? $_SESSION['email']    : null;
        
        $koneksi = connect_db();
        $sql     = "select * from user where email='$email'";
        $query   = mysql_query($sql,$koneksi) or die(mysql_error());
        $data    = mysql_fetch_array($query);
        
        return $data['name'];
        
      }

Double check your field names - when you select everything from the user table, is ‘name’ one of the fields?

Two issues I see:

  1. You still run the query even if the email address is blank - surely you don’t want to do that?
  2. You’re still using the old-style mysql_query() and similar functions, which have been removed from the latest version of PHP.

I would imagine that if you call the function with the session variable not set, that will give the error message you describe. Even if the session variable is set, you should still check to see whether you got any results from the query before you start to use those results. What are you expecting the function to return if the email address is not in the database?

The ‘$email’ is wrong
Instead try $sql = “select * from user where email=”.$email;
or $sql = “select * from user where email={$email}”;
Either will do

either will fail with a MySQL error.

assuming that it is running an older version of PHP - the latest version of PHP will n ot even get that far.

On the many occasions I have a problem like this I
print_r($swl);
var_dump($data);
Examining the result usually shows what I am doing wrong.
The other option is to run the query from inside phpMyAdmin.

I didn’t see a problem with the query, just that it still runs even if the email address is blank, which presumably will return no results and therefore give the error the OP describes. Potentially calls query on null value, uses results without checking there are any. Or maybe column name is wrong. Can’t guess without more information from OP.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.