简体   繁体   中英

How use session variable in sql using php

I have a problem with displaying files added by the logged user. I do not know how to pass the variable correctly to the sql query. Can anyone help me with this?

Currently, the code looks like this:

    <?php
include_once 'dbconnect.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<label>File Uploading With PHP and MySql</label>
</div>
<div id="body">
 <table width="80%" border="1">
    <tr>
    <th colspan="4">your uploads...<label><a href="index.php">upload new files...</a></label></th>
    </tr>
    <tr>
    <td>File Name</td>
    <td>File Type</td>
    <td>File Size(KB)</td>
    <td>View</td>
    </tr>
    <?php
 $sql="SELECT * FROM files";
 $result_set=mysql_query($sql);
 while($row=mysql_fetch_array($result_set))
 {
  ?>
        <tr>
        <td><?php echo $row['file'] ?></td>
        <td><?php echo $row['type'] ?></td>
        <td><?php echo $row['size'] ?></td>
        <td><a href="uploads/<?php echo $row['file'] ?>" target="_blank">view file</a></td>
        </tr>
        <?php
 }
 ?>
    </table>

</div>
</body>
</html>

I am trying to change this record :

$sql="SELECT * FROM files";

to

$sql="SELECT file, type, size FROM files WHERE userId ='$_SESSION[userId]'";

but I still do not get the correct result. Can anyone help?

It looks like the issue with that line is in how you are including the $_SESSION variable. You should have quotes around userId like $_SESSION['userId'] or {$_SESSION['userId']} .

More importantly you should avoid entering variables directly into MySQL queries. I would recommend using MySQLi or PDO instead of MySQL, and look into prepared statements ( here or here , for example).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM