php, Echo mysql 按ID查询

标签 php mysql variables echo

我正在尝试在我的索引上显示数据库的项目,但仅来 self 想要的 ID,而不是整个表。到目前为止,我试过这个但它不起作用:

下载.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>

最佳答案

首先,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 fetches an array both indexed and associative by default, if you don't need the indexed one just go for mysqli_fetch_assoc instead!

mysqli_fetch_array Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.

mysqli_fetch_assoc Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

希望这对您有所帮助!

关于php, Echo mysql 按ID查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16328449/

相关文章:

php - 右 JOIN 与选择结果

php - 如何在从mysql下载的文件的每行末尾添加文本?

php - 将mysql数据库转为php中的pdo类

mysql - MySQL用户定义变量的存储限制

SQL SELECT * FROM OPENROWSET 带变量

javascript - 使用变量指定选择框获取更改选择框的选定值

php - 在另一个 php 文件中选择同一个表

mysql - 来自 MySQL,前往 Oracle : the Pitfalls

MySQL MATCH AGAINST - 处理单引号

php - 将面向对象的数据直接编码为关系数据库中的单行是否被认为是错误的形式?