传递的变量在目标页面上的url中返回null

时间:2015-12-26 08:21:35

标签: php mysql sql url

我现在已经不在思想了。我试图将一个变量从显示所有相册缩略图图像和名称的页面传递到一个页面,该页面将使用该传递的变量显示该库中的所有图片,但该变量在目标页面的URL中为空。我在网络和本网站上看到了类似的案例,我已经应用了这些建议,但它仍然是相同的。这是列出缩略图并传递变量(id)的代码。

    <?php
            include ("config.php");
            $conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD,dbname);
            $albums = mysqli_query($conn,"SELECT * FROM albums");
            if (mysqli_num_rows($albums) == 0) {
                echo "You have no album to display. Please upload an album using the form above to get started. ";
            }
            else{
                echo "Albums created so far:<br><br>";
                echo "<table rows = '4'><tr>";
                while ($thumb = mysqli_fetch_array($albums)) {
                    echo '<td><a href ="view.php?id="'.$thumb['id'].'"/><img src = "'.$thumb['thumbnail'].'"/><br>'.$thumb['album_name'].'<br>'.$thumb['id'].'</a></td>';
                }
                echo "</tr></table>";
            }
     ?>

获取传递变量的代码如下:

<?php
include("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
$db = mysqli_select_db($conn,dbname);
if (isset($_GET['id'])) {
    $album_id = $_GET['id'];
    $pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
    $picQuery = mysqli_query($conn,$pic);
    if (!$picQuery) {
        exit();
    }
    if (mysqli_num_rows($picQuery) == 0) {
        echo "Sorry, no Pictures to display for this album";
}
else{
    echo "Pictures in the gallery:<br><br>";
    while ($result = mysqli_fetch_assoc($picQuery)) {
            echo "<img src='".$result['photo_path']."'/>";
        }
    }
}
?>

请帮助我,因为我花了两天时间试图纠正它。

1 个答案:

答案 0 :(得分:0)

首先,你的代码对sql注入很弱:

$album_id = $_GET['id']; // here
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";

使用$album_id = intval($_GET['id'])或预备语句功能。

其次,在代码中添加调试行,例如:

<?php
include("config.php");
if (isset($_GET['id'])) {
    $album_id = intval($_GET['id']);
    var_dump($album_id); // should print actual passed id

    $conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
    var_dump($conn _id); // should print conn resource value

    $db = mysqli_select_db($conn, dbname);
    var_dump($db); // should print 'true' if db select is ok

    $pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
    $picQuery = mysqli_query($conn, $pic);
    var_dump($picQuery); // should print query resource value

    if (!$picQuery) {
        exit();
    }

    if (mysqli_num_rows($picQuery) == 0) {
        echo "Sorry, no Pictures to display for this album";
    } else {
        echo "Pictures in the gallery:<br><br>";
        while (($result = mysqli_fetch_assoc($picQuery)) !== false) {
            var_dump($result ); // should print fetched assoc array
            echo "<img src='".$result['photo_path']."'/>";
        }
    }
}

请注意$album_id = intval($_GET['id'])while (($result = mysqli_fetch_assoc($picQuery)) !== false)部分

然后关注链接view.php?id=<existing-album-id>并观察调试结果。调试输出与预期的不同之处 - 存在问题。