简体   繁体   English

在PHP / MySQL查询中如何以及在何处编写if语句

[英]How and where to write if statement within PHP/MySQL Query

The following code works well when the correct URL is used like... http://example.com/user.php?id=joe 当使用正确的URL时,以下代码可以很好地工作: http://example.com/user.php ? id=joe

Where I need help is where do I add an if statement and how should it be written to provide either a default landing page or better, an input field so the visitor can retype the user name and submit it to have the correct page load. 我需要帮助的地方是在何处添加if语句,以及如何编写该语句以提供默认的登录页面或更好的登录页面(输入字段),以便访问者可以重新输入用户名并将其提交以正确加载页面。

<?php
$pdo = new PDO('mysql:host=localhost;dbname=users', 'root', '');

// retrieve member's data
$ps = $pdo->prepare("SELECT * FROM members WHERE id = ?");
    if(isset($_GET["id"])) {
    $ps->execute(array($_GET["id"]));
    }

$result = $ps->fetch(PDO::FETCH_ASSOC);

extract($result);

echo $First_Name . ' - ' . $Email; 

Any help? 有什么帮助吗?

if(!empty($_GET['id'])) {
  // YOUR PREVIOUS CODE HERE
} else {
  // REDIRECT CODE HERE
}

I assume you'd want to wrap all the code with the if statement so it doesn't run unless an id is present. 我假设您想用if语句包装所有代码,因此除非存在id,否则它不会运行。

<?php
    if( isset( $_GET['id'] ) ) {
        //retrieve member data here and render normal page
    }
    else {
        //render landing page
    }
?>

It might be wise to put the code for rendering the two different pages into different functions to help with organization as well. 将用于呈现两个不同页面的代码置于不同的功能中以帮助组织也可能是明智的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM