使用$ searchEscaped显示特定数据

时间:2016-05-15 17:02:28

标签: php html mysql css mysqli

我正在使用$ searchEscaped来允许用户“查看他们的个人资料”,但这个结果对我不起作用。这是我的代码:

这是用户点击查看其个人资料的链接

 <li><a href="profile2.php?username=<?php echo $userRow['username'];?>">View Profile</a></li>

然后将它们发送到profile.php页面。这是下面的。

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection

$searchEscaped = $conn->real_escape_string($_GET['username']);
if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
} 

$res=mysql_query("SELECT username , image FROM users WHERE username='$searchEscaped'");
$userRow=mysql_fetch_array($res);



$conn->close();
?>  

<?php echo $userRow['username']; ?>
<?php echo $userRow['image']; ?>

任何帮助都会很棒。谢谢!

2 个答案:

答案 0 :(得分:1)

<?php   
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "database";

        // Create connection
        $conn = mysqli_connect($servername, $username, $password, $dbname);
        // Check connection


        if (!$conn) {
             die("Connection failed: " . mysqli_connect_error();
        }

        $searchEscaped = mysqli_real_escape_string($conn, $_GET['username']);
        $res=mysqli_query($conn, "SELECT username , image FROM users WHERE username='$searchEscaped'");
        $userRow=mysqli_fetch_array($res);



        mysqli_close($conn);
        ?>

        <?php echo $userRow['username']; ?>
        <?php echo $userRow['image']; ?>

答案 1 :(得分:0)

您正在混合mysqlmysqli。毫无疑问,这是你问题的原因。

我已将您的代码转换为PDO,以保护您免受SQL注入攻击。

<?php
$username = "root";
$password = "";

$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);

$searchEscaped = $_GET['username'];

$stmt = $con->prepare("SELECT username, image FROM users WHERE username=:searchEscaped");
$stmt->bindParam(':searchEscaped', $searchEscaped);
$stmt->execute();
$userRow = $stmt->fetch(); 

echo $userRow['username']; 
echo $userRow['image'];
?>