簡體   English   中英

兩段幾乎完全相同的代碼..一個起作用,另一個不起作用

[英]Two near-identical pieces of code.. one works, the other doesn't

下面的代碼工作正常,它從文件夾中隨機選擇一個圖像,並將其作為背景分配給生成的Div。 這可行。 如果我第二次使用此代碼,但僅使用它來放置隨機圖像的img-src,這也可以工作。 但是,以與第一種相同的方式使用代碼會破壞站點。 我究竟做錯了什么?

 <!-- BEGIN FEATURED 1 -->

                             <?php
try {
    $conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch (PDOException $e) {
    echo $e->getMessage();
    echo 'Could not establish a connection to the database.';
}

$query = $conn->prepare('SELECT `articleid`,`title`  FROM `news_articles` WHERE  featured = 1 ORDER BY RAND() LIMIT 1');
$array = array(
    'N'
);
$query->execute();

$results = $query->fetchAll(PDO::FETCH_COLUMN, 0);
foreach ($results as $row) {
}

$image = get_rand_img('images/featured_images/csgo/');
$title = $result['title'];
echo '<a href="index.php?viewarticle=1&articleid=' . $row . '">';?>
<div id="featured-image" style="height: 267px; width: 292px; background:url(/images/featured_images/csgo/<?php echo $image ?>)">
<?php

$result = $conn->prepare("SELECT `articleid`,`title`,`short_title` FROM `news_articles` WHERE articleid=$row");
    $result->execute();
    $rows = $result->fetch();
        echo '<div class="featuredtitle1">';
        echo $rows['short_title'];
        echo '</div>';
        echo '</div>';
        echo '</a>';

?>

下面的代碼破壞了站點。.(如您所見,目前我已將其注釋掉)。

<!-- BEGIN FEATURED 2 (Disabled) -->

            <?php
/*
try {
    $conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch (PDOException $e) {
    echo $e->getMessage();
    echo 'Could not establish a connection to the database.';
}

$query = $conn->prepare('SELECT `articleid` FROM `news_articles` WHERE  featured = 1 ORDER BY RAND() LIMIT 1');
$array = array(
    'N'
);
$query->execute();

$results = $query->fetchAll(PDO::FETCH_COLUMN, 0);
foreach ($results as $row) {
}

$image = get_rand_img('images/featured_images/dota/');
$title = $result['title'];
echo '<a href="index.php?viewarticle=1&articleid=' . $row . '">';?>
<div id="featured-image2" style="height: 267px; width: 292px; background:url(/images/featured_images/dota/<?php echo $image ?>)">
<?php

$result = $conn->prepare("SELECT `articleid`,`title`,`short_title` FROM `news_articles` WHERE articleid=$row");
    $result->execute();
    $rows = $result->fetch();
        echo '<div class="featuredtitle2">';
        echo $rows['short_title'];
        echo '</div>';
        echo '</div>';
        echo '</a>';
*/
?>

我不明白為什么第一段代碼很好,但是再次復制會破壞代碼?

在您編輯評論之前,我看到了有關將對象作為數組訪問的致命錯誤。 嘗試從中更改代碼:

$results = $query->fetchAll(PDO::FETCH_COLUMN, 0);

對此:

$results = $query->fetchAll(PDO::FETCH_ASSOC);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM