【问题标题】:SQL query to return mixed tables用于返回混合表的 SQL 查询
【发布时间】:2014-07-25 15:13:10
【问题描述】:

你好我有以下网址

http://www.test.nl/test.php?itemnr=123

在我的数据库中的表items2 中,我的列是:

itemnr | itemId | Description | etc

因为我想在这个页面上显示 itemnr 和 itemId 我有这个查询:

<?php
$itemnummer = intval($_GET['itemnr']);
$itemIDnummer = "SELECT DISTINCT itemId from items2 where itemnr = '" .$itemnummer. "'";
$resultaat = mysql_query($itemIDnummer) or die(mysql_error());

echo "$resultaat"; 
?>    

谁能看出我的错?

【问题讨论】:

  • 什么故障?什么奇怪的结果?你有错误吗?一个空白屏幕?您当前正在尝试直接打印结果集;您需要使用mysql_fetch_array 之类的内容对其进行迭代以获取数据。您也对 SQL 注入持开放态度;如果您现在刚刚学习,则应该考虑使用 PDO 而不是已弃用的 mysql_
  • 这段代码是gravely vulnerable to sql injections,考虑用mysqli或pdo代替mysql。
  • 另外,$resultaat 不是字符串,所以即使查询成功也会抛出错误。可能出现“数组到字符串转换”错误。
  • @BasSchreuder - 你需要类似while ($row = mysql_fetch_array($resultaat)) { echo $row['itemId']; }
  • @BasSchreuder - 我同意。但是,如果您现在正在学习 PHP,则可以直接跳过使用 mysql_ 函数并学习 PDO。

标签: php mysql variables get


【解决方案1】:

添加使您的代码看起来像这样

<?php
$itemnummer = intval($_GET['itemnr']);
$itemIDnummer = "SELECT DISTINCT itemId from items2 where itemnr = '" .$itemnummer. "'";
$resultaat = mysql_query($itemIDnummer) or die(mysql_error());
$fetchaat = mysql_fetch_assoc($resultaat);

echo $fetchaat["itemId"]; 
?>

更新问题:

因为我想在这个页面上显示 itemnr 和 itemId 我有这个查询:

<?php
$itemnummer = intval($_GET['itemnr']);
$itemIDnummer = "SELECT DISTINCT itemId, itemnr from items2 where itemnr = '" .$itemnummer. "'";
$resultaat = mysql_query($itemIDnummer) or die(mysql_error());
$fetchaat = mysql_fetch_assoc($resultaat);

echo $fetchaat["itemId"]; 
echo $fetchaat["itemnr"];
?>

【讨论】:

  • 正如对 OP 的注释一样,您的代码容易受到 SQL 注入攻击
  • 当 OP 询问“谁能看出我的错”时,我注意到他试图回显数组。回声表明了他的意图,如果他觉得他的 sql 语句容易受到注射,那么他会要求这样做。
  • @Barranka 不,不是。请参阅我对这个问题的评论。
  • @DanceSC - 不显示错误,但显示空白“页面”。不打印任何结果。
  • 也许,只是也许,因为我使用 intval 它只允许槽数,而我正在测试的这个特定 itemnr 包含字符。将 intval 替换为 ...?
猜你喜欢
  • 2021-12-26
  • 1970-01-01
  • 2021-04-17
  • 2017-05-21
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-18
  • 2013-08-18
相关资源
最近更新 更多