【问题标题】:Call row with link and Id [closed]带有链接和 ID 的调用行 [关闭]
【发布时间】:2013-05-17 06:57:02
【问题描述】:

我的问题是,如何使用 url 栏中的行 ID 定位和回显特定行的内容。 Example: Row 4: name: bob email: 123@abc.com,当有人访问时,让我们举个例子:website.com/123.php?=4(不必完全像这样)它回显名称:bob 电子邮件:123@abc.com。如果您需要了解更多,请询问。

More of an example:
Row: 9999
name: smith
email: smith@email.com
password: smith123

用户访问www.website.com/?9999www.website.com/123.php?=9999(或任何类型的链接 - 不是具有行号/id 的链接),然后在页面上回显,例如: 感谢访问页面。联系他,谢谢。 基本上我希望能够通过在url栏中使用它的行号来调用某一行的信息。

【问题讨论】:

  • 不要使用 www.website.com/123.php?=9999,而是使用 www.website.com/123.php?rowid=9999。然后在 php 中使用 $_GET['rowid'] 函数来获取该 id
  • 请记住,数据库中的“行”*没有内在顺序”。如果您想搜索“id=4”……那么您的表需要有一个名为“id”的列,并且其中一个(并且只有一个)行的值应为“4”。这称为“主键”。相应的 SQL 查询将类似于 select * from mytable where id=4;

标签: php mysql row echo


【解决方案1】:

例如,使用$_GET[] 方法从 URL 中获取值,然后从数据库中获取该行

www.domain.com/page.php?id=4

所以现在在page.php 上使用这段代码

if(!empty($_GET['id'])) {
   $id = $_GET['id']; //Don't Forget to sanitize it before using it in your query
   //Check whether id exists like
   $is_valid_id = mysqli_query($connection, "SELECT id FROM table_name WHERE id = $id");
   if(mysqli_num_rows($is_valid_id) != 1) {
      //Redirect
   }
} else {
   //Redirect or throw some error
}

现在使用这个 id 通过查询来获取一行

$query = mysqli_fetch_array(mysqli_query($connection, "SELECT * FROM table_name 
                                                       WHERE id = $id"));

现在你可以轻松echo出数据了

/* Assuming first_name and last_name as column names */
echo $query['first_name']; //Bob
echo $query['last_name']; //Doe
/* And so on... */

【讨论】:

    【解决方案2】:

    只需使用查询字符串:

    www.url.com/page.php?id=121
    

    使用 $_GET 获取 id

    if (isset($_GET['id']))
    {
    
    
    //    fetch and display the information with      database Query 
    
    $con=mysqli_connect("example.com","peter","abc123","my_db");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    
    $result = mysqli_query($con,"SELECT * FROM Persons where id = " . $_GET['id']);
    
    while($row = mysqli_fetch_array($result))
      {
      echo $row['name'] . " " . $row['email'];
      echo "<br>";
      }
    
    mysqli_close($con);
    
    
    
    }
    

    【讨论】:

    • 您至少应该将 id 转换为 int 以防止注入
    猜你喜欢
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 2016-07-14
    • 2017-12-08
    • 1970-01-01
    • 2019-03-24
    • 2012-02-15
    相关资源
    最近更新 更多