【问题标题】:Echo data from two different tables in database: echo data 2nd table not working来自数据库中两个不同表的回显数据:回显数据第二个表不起作用
【发布时间】:2014-08-09 03:29:50
【问题描述】:

我想从我的数据库的 2 个表中回显一些数据,但我的第二个表“图像”的数据不会显示。

我得到了什么:

  • 1 个数据库(没有连接问题,没关系)
  • 2 表:
    • “文章”,列(id、标题、文本)
    • “images”,列(idimage、image-title、image-path)
  • 我想在一个网页上显示这两个表中的数据
  • 在 div“content-text”中,我需要显示第二个表“images”中的一些图像

网页:

<div id="wrapper">

    <?php
    include_once $_SERVER["DOCUMENT_ROOT"] . "/config.php";
    $title = str_replace ('-', ' ', $_GET['title']);
    $sql = "SELECT * FROM `articles` WHERE title = '$title'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
    ?>

    <div class="content-title">
        <?php echo $row['title'];?>
    </div>

    <div class="content-text">
        <?php echo $row['text'];?>

        <?php 
        $imagesql = "SELECT * FROM `images` WHERE image-title = '$title'";
        $imageresult = $conn->query($imagesql);
        if ($imageresult->num_rows > 0) {
        while($imagerow = mysqli_fetch_array($imageresult)) {
        ?>

        <a class="swipebox" href="<?php echo $imagerow['image-path'];?>" title="<?php echo $imagerow['image-title'];?>">
        <img alt="image" src="<?php echo $imagerow['image-path'];?>"></a>

        <?php
        }// end while
        }// end if
        else {
        echo '0 results';
        }// end else
        ?>

    </div> //end content-text

    <br>
    <?php
    }// end while
    }// end if
    else {
    echo '0 results';
    }// end else
    ?>

    <?php
    // close the connection
    $conn->close();
    ?>

</div> // end wrapper

确切的问题:

从表“文章”中回显标题和文本工作正常,但是当我尝试从表“图像”中回显数据时出现问题,因为它给了我错误“0 个结果”。 PHP 和 SQL 对我来说仍然是新事物,我没有找到解决方案...

【问题讨论】:

  • image-title 用反引号括起来,作为您的WHERE image-title。 SQL 正在评估它(连字符等于减号)作为一个数学问题。那,或者更改连字符并用下划线重命名。
  • image-titleimage MINUS title
  • ...就像我说的 ;-)
  • @Fred -ii- 显然我还需要学习很多关于 sql 的知识...非常感谢!现在可以正常使用了。
  • 不客气,斯坦,干杯。

标签: php mysql sql database


【解决方案1】:

在 MySQL 中使用带反引号的空格、连字符(等)转义标识符:

SELECT * FROM `images` WHERE `image-title` = '$title'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多