php,Echo通过ID查询mysql

时间:2013-05-02 00:15:10

标签: php mysql variables echo

我正在尝试在索引上显示数据库的项目,但只是来自我想要的id,而不是整个表。到目前为止,我已经尝试了这个,但它不起作用:

的download.php

<?php

$id = $_GET['id'];

$con=mysqli_connect("kennyist.com","user","pass","table");

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM `wp_wpfb_files` WHERE `file_id`=" . $id);

$row = mysqli_fetch_array($result)

mysqli_close($con);
?>

我试图像这样回应它(之前看到类似的东西):

<div class="version"><?php echo('download.php?id=27', $row['file_version']);?></div>

4 个答案:

答案 0 :(得分:1)

首先,mysqli_connect现在位于deprecated mysqli functions之下!这意味着,最好转而使用面向对象的版本!

以下是您如何执行此操作的示例:

$link = new mysqli ("kennyist.com","user","pass","table");

/* 
if id is a string then go for this version 

$id = $link->real_escape_string($_GET['id']);
*/

$id = intval($_GET['id']); // if id is integer, this is better 

if ( $link->errno )
{
    echo "Failed to connect to MySQL: {$link->error}";
}

$result = $link->query("SELECT * FROM `wp_wpfb_files` WHERE `file_id` = $id");

if ( $result->num_rows ) $row = $result->fetch_assoc();

$link->close();

更好的方法是使用准备好的语句,但是如果你不熟悉它们,那么一开始就会有点棘手!无论如何,现在你可以按要求做事了!

<div class="version">
    <?php echo "download.php?id=27{$row['file_version']}"; ?>
</div>

你想要回应的东西仍然需要一些事情,以防止错误发生:

  • file_version必须是表格中的列
  • 必须设置
  • $_GET['id']才能设置正确的$id
  • 表格中必须有相应file_id
  • 的记录

注意

echo "download.php?id=27{$row['file_version']}";

总是会在任何分页上打印出相同的id,你可能想要的是将正确的file_id转发到你的download.php页面!您可以使用以下内容执行此操作:

echo "download.php?id={$row['file_id']}&version={$row['file_version']}";

提示

  默认情况下,

mysqli_fetch_array获取索引和关联的数组,如果您不需要索引的数组,只需转到mysqli_fetch_assoc

     
    

mysqli_fetch_array返回与获取的行对应的数组,如果结果参数表示的结果集不再有行,则返回NULL。

         

mysqli_fetch_assoc返回与获取的行对应的关联数组,如果没有其他行,则返回NULL。

  

希望这有帮助!

答案 1 :(得分:-1)

SELECT " . $id . "  FROM wp_wpfb_files

如果id = 27,您的查询将显示为

SELECT 27 FROM wp_wpfb_files

我认为您需要查询:

SELECT id, file_version FROM wp_wpfb_files WHERE id = $id

答案 2 :(得分:-1)

编辑:nvm我的回答,操作编辑了他的问题以改变他的查询,就像在我的回答中一样

尝试像这样修改$ result分配

$result = mysqli_query($con, "SELECT file_version FROM wp_wpfb_files WHERE id = ".$id);

编辑:删除了代码,假定id是一个字符串

答案 3 :(得分:-1)

请尝试使用此输出

<div class="version"><?php echo 'download.php?id=27' . $row['file_version'];?></div>

假设$ row ['file_version'] ='fred',这应该是这样的:

<div class="version">download.php?id=27fred</div>

这对我来说没有多大意义,但也许对你有用。

相关问题