SESSIONS PHP and MySql

0

I am learning sessions in PHP, I already have my session created, in a login I can already enter with real data from a database, in this case the user and password, in my page where they are already registered I put <?php echo $_SESSION['session_username'];?> and it gives me the name of the user who entered, all right, my question is:

In this way, you can pass an image, which can be found in the users table? or Would you have to make another type of query to print it?

    
asked by David Calva 16.06.2016 в 07:36
source

2 answers

1

Yes you can use $_SESSION to show images:

If you want to upload the image from BD

In the catalog (substituting the 1 for the ID you need):

<body>
    <img src="getImage.php?id=1" width="60" height="60" />
</body>

getImage.php:

If you already have the image in a form

First save the image you need like this:

<?php
    $filename    = $_FILES["picture"]["tmp_name"];
    $destination = "upload/" . $_FILES["picture"]["name"]; 
    move_uploaded_file($filename, $destination);
    $_SESSION['imagen'] = $destination; //Se guarda la dirección de la imagen en la variable de SESSION

And finally show the image where you want:

<?php
    session_start();
?>
<div>
  <img src="<?php echo $_SESSION['imagen']; ?>" alt="picture"/>
</div>
    
answered by 16.06.2016 в 09:00
1
  

My question is if in this way you can pass an image that is found in the users table

We imagine that a simple query brings all the results we want in an array:

SELECT id, username, email, role, image FROM users WHERE id=1

The resulting array could be something like this:

$result = array(
    'id'       => 1,
    'username' => 'myusername',
    'email'    => '[email protected]',
    'role'     => 'admin',
    'image'    => '/src/images/myimage.jpg'
);

It is interesting (recommendable) to maintain a good structure and order the session variables. As you advance in the development, you make more and more use of them and they tend to increase their quantity.

An example with a certain order would be something like this:

$_SESSION = array(
    'user' => array(
        'id'       => $result['id'],
        'username' => $result['username'],
        'email'    => $result['email'],
        'role'     => $result['role'],
        'image'    => $result['image'],
    ),
    'data' => array(
        'last_visit' => 9786767866,
        'theme'      => 'blue',
        //...
    ),
    //...
);

It would only be possible to recover them where you need them

$user     = $_SESSION['user'];
$data     = $_SESSION['data'];
$username = $user['username'];
$avatar   = $user['image'];

And put them in the view where you need them (I have assumed that is user and avatar as an example).

<ul class="inline">
    <li><?php echo $username; ?></li>
    <li><img src="<?php echo $avatar; ?>" alt="Avatar <?php echo $username; ?>"</li>
</ul>
    
answered by 16.06.2016 в 10:04