Samuel S.
Samuel S.

Reputation: 19

Problems with MySQL recognizing session user in selection

I'm having the problem of mySQL not recognizing the session user when I select data from a table. Can someone please point me in the correct position on what I need to do to fix this?

$sql1="SELECT * FROM `Bookings` WHERE `username`={$_SESSION['user']}";

This is what my code looks like, but it never fetches the data and just remains blank.

Upvotes: 0

Views: 38

Answers (2)

Jahid Mahmud
Jahid Mahmud

Reputation: 1136

You can use

$user=$_SESSION['user']; $sql1="SELECT * FROM Bookings WHERE username= '$user'";

Hopefully This will solve your problem

Upvotes: 0

samayo
samayo

Reputation: 16495

First you should check if $_SESSION['user'] is initialized or has any value.

Second, it is better to assign the session user to a variable, so as to avoid some ugly issues related to escaping quotes, in the future. Don't just directly dump your session within your mysql statement.

$user_session = $_SESSION['user']; 
$sql1="SELECT * FROM `Bookings` WHERE `username`= $user_session";

#Edit:

as @Dann pointed out, it's must better and safer to user prepared statement, with either the mysqli/pdo API. Here is a simple example in PDO.

First you have to connect to your database:

try {
    $db = new \PDO("mysql:host=localhost;dbname=xx;charset=utf8", "xx", "xx", [
        PDO::ATTR_EMULATE_PREPARES => false, 
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]); 
} catch(\PDOException $e){
    echo "Error connecting to mysql: ". $e->getMessage();
}

Then simply fetch the booking as seen below.

$user_session = $_SESSION['user']; 

try{
    $stmt = $db->prepare("SELECT * FROM Bookings WHERE username = ?");
    $result = $stmt->execute([$user_session]);

    if($result){
      // show booking
    }

} catch(\PDOException $e){
    echo "Counld not get user bookings. error: " . $e->getMessage(); 
}

Now your query is safer from mysql injection attacks, and connection errors will only throw exceptions, instead of showing potentially harmful errors.

Upvotes: 1

Related Questions