哪个 WHILE LOOP 是 4 中的有效输出?

如何解决哪个 WHILE LOOP 是 4 中的有效输出?

我想知道以下 4 个中哪个 WHILE LOOP 是正确的。 如果这 4 个中的任何一个无效,那么我想知道为什么以及如何修复它们。欢迎代码示例。不止一个。

1.

$i = '1';
while($i<=$total_pages)
{
    $query_string_2 = '&page=' .intval($i);
    $url = $path .htmlentities($query_string_1) .htmlentities($query_string_2); //Full URL With $_REQUEST params (Query Strings): https://localhost/Templates/url_encode_Template.php?find=keyword&tbl=links&col=keyword&max=100&page=1

if($page == $i)
{
    //Bold the current Page numbered link.
    echo '<a href=' .'"' .$url .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>';
}
else
{
    echo '<a href=' .'"' .$url .'"' .'>' .intval($i) .'</a>';
}
$i++;
}

$i = '1';
while($i<=$total_pages)
{
    $query_string_2 = '&page=' .intval($i);
    
if($page == $i)
{
    //Bold the current Page numbered link.
    echo '<a href=' .'"' ."$path" .htmlentities($query_string_1) .htmlentities($query_string_2) .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>';
}
else
{
    echo '<a href=' .'"' ."$path" .htmlentities($query_string_1) .htmlentities($query_string_2) .'"' .'>' .intval($i) .'</a>';
}
$i++;
}
$i = '1';
while($i<=$total_pages)
{
    $query_string_2 = '&page=' .intval($i);
    $url = $path .$query_string_1 .$query_string_2; //Full URL With $_REQUEST params (Query Strings): https://localhost/Templates/url_encode_Template.php?find=keyword&tbl=links&col=keyword&max=100&page=1

if($page == $i)
{
    //Bold the current Page numbered link.
    echo '<a href=' .'"' .htmlspecialchars($url) .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>';
}
else
{
    echo '<a href=' .'"' .htmlspecialchars($url) .'"' .'>' .intval($i) .'</a>';
}
$i++;
}

$i = '1';
while($i<=$total_pages)
{
    $query_string_2 = '&page=' .intval($i);
    $url = $path .htmlentities($query_string_1) .htmlentities($query_string_2); //Full URL With $_REQUEST params (Query Strings): https://localhost/Templates/url_encode_Template.php?find=keyword&tbl=links&col=keyword&max=100&page=1

if($page == $i)
{
    //Bold the current Page numbered link.
    echo '<a href=' .'"' .htmlspecialchars($url) .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>';
}
else
{
    echo '<a href=' .'"' .htmlspecialchars($url) .'"' .'>' .intval($i) .'</a>';
}
$i++;
}

如果您能向我展示如何编写代码示例,我将不胜感激。 上面的代码是分页的一部分,它与 1234 等页码相呼应,就像您在 google 搜索结果页面底部看到的那样。

代码上下文: 嗯

<form method = 'GET' action = "">
<label for='find'>Find</label>
<input type='text' name='find' id='find'>
<br>
Table:
<input type='radio' name='table' id='sale'><label for='table'>Websites On Sale</label>
<input type='radio' name='table' id='sold'><label for='table'>Websites Sold</label>
<input type='radio' name='table' id='links'><label for='table'>Links</label>
<br>
<label for="column">Column:</label>
<select name="column" id="column">
    <option value=""></option>
    <option value="domain">Domain</option>
    <option value="email">Email</option>
    <option value="submission_id">Submission Id</option>
    <option value="url">Url</option>
    <option value="anchor">Anchor</option>
    <option value="description">Description</option>
    <option value="keywords">Keyword</option>
    </select>
<br>
<button type='submit'>Search!</button>
</form>

PHP

<?php

//ERROR REPORTING FOR DEVMODE ONLY.
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);

//MYSQLI CONNECTION.
mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);

$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';

if(!$conn = mysqli_connect("$server","$user","$password","$database"))
{
    echo 'Mysqli Connection Error' .mysqli_connect_error($conn);
    echo 'Mysqli Connection Error Number' .mysqli_connect_errno($conn);
}

if(!mysqli_character_set_name($conn) == 'utf8mb4')
{
    echo 'Initial Character Set: ' .mysqli_character_set_name($conn);
    mysqli_set_charset("$conn",'utf8mb4');
    echo 'Current Character Set: ' .mysqli_character_set_name($conn);
}


//SECTION: WHITE-LISTS.
//Valid list of Mysql Tables.
$tables_white_list = array('sale','sold','links');
//Valid list of Mysql Table Columns.
$columns_white_list = array('email','domain','url','anchor','description','keyword');
//Banned Words List. Users cannot search these keywords.
$blacklisted_words = array('prick','dick');

//SECTION: VALIDATE SERP URL.
//Check if "table" exists or not in Url's Query String.
if(ISSET($_REQUEST['table']) && !empty(trim($_REQUEST['table'])) && is_string(trim($_REQUEST['table'])))
{
    if(in_array(trim($_REQUEST['table']),$tables_white_list)) //MySql Tbl to Search.
    {
        $tbl = trim($_REQUEST['table']);
    }
    else
    {
        die('Invalid Table!');
    }
}
else
{
    die('Select Table!');
}

//Check if "column" exists or not in Url's Query String.
if(ISSET($_REQUEST['column']) && !empty(trim($_REQUEST['column'])) && is_string(trim($_REQUEST['column'])))
{
    if(in_array(trim($_REQUEST['column']),$columns_white_list)) //MySql Tbl Col to search.
    {
        $col = trim($_REQUEST['column']);
    }
    else
    {
        die('Invalid Column!');
    }
}
else
{
    die('Select Column!');
}

//Check if "search term" exists or not in Url's Query String.
if(!ISSET($_REQUEST['find']) || empty(trim($_REQUEST['find'])) && !is_string(trim($_REQUEST['find'])) || !is_int(trim($_REQUEST['find']))) //Using $_REQUEST[] for both $_REQUEST['POST'] & $_REQUEST['REQUEST'].
{
    die('Enter Keywords to search!');
}
else
{
    if(in_array(trim($_REQUEST['find']),$blacklisted_words)) //Keyword(s) to search.
    {
        die('Your search terms contains a banned word! Try some other keywords');
    }
    else
    {
        $find = trim($_REQUEST['find']); //Not trimming or ridding trailing spaces here as user's keyword (eg. foreign keywords or symbols) may actually contain such spaces.   
                
    if($col=='submission_id')
    {
        if(!is_INT($find))
        {
            die('Enter a valid Submission Number! Can only be a numerical value.');
        }
        else
        {
            $submission_id = $find;
        }
    }
    
    if($col=='email')
    {
        if(!filter_input(INPUT_GET,"email",FILTER_VALIDATE_EMAIL))
        {
            die('Enter a valid Email!');
        }
        else
        {
            $email = $find;
        }
    }
    
    if($col=='domain')
    {
        if(!filter_input(INPUT_GET,"domain",FILTER_VALIDATE_DOMAIN))
        {
            die('Enter a valid Domain!');
        }
        else
        {
            $domain = $find;
        }
    }
    if($col=='url')
    {
        if(!filter_input(INPUT_GET,"url",FILTER_VALIDATE_URL))
        {
            die('Enter a valid Url!');
        }
        else
        {
            $url = $find;
        }
    }
    
    if($col=='anchor')
    {
        if(!filter_input(INPUT_GET,"anchor",FILTER_VALIDATE_STRING)) //HOW TO VALIDATE STRING ?
        {
            die('Enter a valid Description!');
        }
        else
        {
            $description = $find;
        }
    }
    
    if($col=='description')
    {
        if(!filter_input(INPUT_GET,"description",FILTER_VALIDATE_STRING)) //HOW TO VALIDATE STRING ?
        {
            die('Enter a valid Description!');
        }
        else
        {
            $description = $find;
        }
    }
    
    if($col=='keyword')
    {
        if(!filter_input(INPUT_GET,"keyword",FILTER_VALIDATE_STRING))
        {
            die('Enter a valid Keyword!');
        }
        else
        {
            $keyword = $find;
        }
    }
}
}

$max = (!empty($_REQUEST['max']) and intval($_REQUEST['max']) > 0)
? intval($_REQUEST['max']) : 1;

$page_no = (!empty($_REQUEST['page']) and intval($_REQUEST['page']) > 0)
? intval($_REQUEST['page']) : 1;

//SECTION: QUERY DATABASE FOR KEYWORD COUNT.
$query = "SELECT COUNT(id) From links WHERE keyword = ?";
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
    mysqli_stmt_bind_param($stmt,'s',$find);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt,$row_count);
    if(mysqli_stmt_fetch($stmt))
    {
        echo 'Row Count: ' .$row_count; echo '<br>';    
    }
    else
    {
        echo 'Record fetching failed!';
        echo 'Error: ' .mysqli_stmt_error($conn);
        echo 'Error: ' .mysqli_stmt_errno($conn);
    }
    mysqli_stmt_close($stmt);
}
else
{
    echo 'find Preparation Failed!';
}
//mysqli_close($conn);
echo '<b>'; echo __LINE__; echo '</b>'; echo '<br>';


//SECTION: QUERY DATABASE FOR SEARCH-TERM MATCHES.
echo $offset = ($page*$max)-$max; echo '<br>';
$query = "SELECT id,date_and_time,name,age,zip,phone,mobile,fax,email,domain,url,description From links WHERE $tbl = ? LIMIT $offset,$max";
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$find);
    mysqli_stmt_execute($stmt);
    if($result = mysqli_stmt_get_result($stmt))
    {
        $columns = mysqli_fetch_array($result);
        
    $submission_id = $columns['id'];
    $submission_date_and_time = $columns['date_and_time'];
    $email = $columns['email'];
    $domain = $columns['domain'];
    $url = $columns['url'];
    $anchor = $columns['anchor'];
    $description = $columns['description'];
    $keyword = $columns['keyword']; 
            
    echo 'Submission Id: ' .$submission_id; echo '<br>';
    echo 'Submission Date And Time: ' .$submission_date_and_time; echo '<br>';
    echo 'Email: ' .$email; echo '<br>';
    echo 'Domain: ' .$domain; echo '<br>';
    echo 'Url: ' .$url; echo '<br>';
    echo 'Anchor: ' .$anchor; echo '<br>';
    echo 'Description: ' .$description; echo '<br>';
    echo 'Keyword: ' .$keyword; echo '<br>';
    //WHICH OF THE FOLLOWING TWO ECHOES IS BEST ?
    echo 'Link: <a href=' .'"' .strip_tags($url) .'"' .'>' .'<b>' .strip_tags($url) .'</b>' .'</a>'; echo '<br>'; //Need to add your aided code on this line before echoing third party submitted links on my page. Your code needs to detect url structure and break them up into pieces and apply the appropriate php function (urlencode(),raw_urlencode(),htmlentities(),htmlspecialchars(),intval() on the appropriate pieces.
    echo 'Link: <a href=' .'"' .htmlspecialchars($url) .'"' .'>' .'<b>' .htmlspecialchars($url) .'</b>' .'</a>'; echo '<br>'; //Need to add your aided code on this line before echoing third party submitted links on my page. Your code needs to detect url structure and break them up into pieces and apply the appropriate php function (urlencode(),intval() on the appropriate pieces.
}
else
{
    //Error Messages for Production Mode only.
    echo 'Record fetching failed!';
    echo 'Error: ' .mysqli_stmt_error($stmt);
    echo 'Error: ' .mysqli_stmt_errno($stmt);
}
mysqli_stmt_close($stmt);
}
mysqli_close($conn);


//SECTION: PAGINATION SECTION TO NUMBER THE SERPS AND LINK THEM.
$total_pages = ceil($row_count/$max);
//Grab the current page's url.
$selfpage = basename(__FILE__,''); //Echoes: url_encode_Template.php. Does not fetch the url's query terms (params & their values absent).
//Encode the File Path.
$path = rawurlencode($selfpage);
//Encode the Query String in the url.
$query_string_1 = '?find=' .urlencode($find) .'&table=' .urlencode($table) .'&column=' .urlencode($column) .'&max=' .intval($max);

//1. WHICH WHILE LOOP IS BEST ?
$i = '1';
while($i<=$total_pages)
{
    $query_string_2 = '&page=' .intval($i);
    $url = $path .htmlentities($query_string_1) .htmlentities($query_string_2); //Full URL With $_REQUEST params (Query Strings): https://localhost/Templates/url_encode_Template.php?find=keyword&tbl=links&col=keyword&max=100&page=1

if($page == $i)
{
    //Bold the current Page numbered link.
    echo '<a href=' .'"' .$url .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>';
}
else
{
    echo '<a href=' .'"' .$url .'"' .'>' .intval($i) .'</a>';
}
$i++;
}

echo '<br>';

//2. WHICH WHILE LOOP IS BEST ?
$i = '1';
while($i<=$total_pages)
{
    $query_string_2 = '&page=' .intval($i);
    
if($page == $i)
{
    //Bold the current Page numbered link.
    echo '<a href=' .'"' ."$path" .htmlentities($query_string_1) .htmlentities($query_string_2) .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>';
}
else
{
    echo '<a href=' .'"' ."$path" .htmlentities($query_string_1) .htmlentities($query_string_2) .'"' .'>' .intval($i) .'</a>';
}
$i++;
}

//3. WHICH WHILE LOOP IS BEST ?
$i = '1';
while($i<=$total_pages)
{
    $query_string_2 = '&page=' .intval($i);
    $url = $path .$query_string_1 .$query_string_2; //Full URL With $_REQUEST params (Query Strings): https://localhost/Templates/url_encode_Template.php?find=keyword&tbl=links&col=keyword&max=100&page=1

if($page == $i)
{
    //Bold the current Page numbered link.
    echo '<a href=' .'"' .htmlspecialchars($url) .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>';
}
else
{
    echo '<a href=' .'"' .htmlspecialchars($url) .'"' .'>' .intval($i) .'</a>';
}
$i++;
}

echo '<br>';

//4. WHICH WHILE LOOP IS BEST ?
$i = '1';
while($i<=$total_pages)
{
    $query_string_2 = '&page=' .intval($i);
    $url = $path .htmlentities($query_string_1) .htmlentities($query_string_2); //Full URL With $_REQUEST params (Query Strings): https://localhost/Templates/url_encode_Template.php?find=keyword&tbl=links&col=keyword&max=100&page=1

if($page == $i)
{
    //Bold the current Page numbered link.
    echo '<a href=' .'"' .htmlspecialchars($url) .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>';
}
else
{
    echo '<a href=' .'"' .htmlspecialchars($url) .'"' .'>' .intval($i) .'</a>';
}
$i++;
}

echo '<br>';

?>

如果我上面的代码有任何其他严重错误,那么我很感激你更正的代码示例。

谢谢!

编辑 1: 更新1: 从这个线程的反馈来看,我相信我不应该在使用 urlencode() 的 url 上使用 htmlentities() 或 htmlspecialchars()。因此,以下是我的最新更新。我现在想要更多你的反馈......

WHILE LOOP 我已经更新...

//SECTION: PAGINATION SECTION TO NUMBER THE SERPS AND LINK THEM.
$total_pages = ceil($row_count/$max);
//Grab the current page's url.
$selfpage = basename(__FILE__,''); //Echoes: url_encode_Template.php. Does not fetch the url's query terms (params & their values absent).
//Encode the File Path.
$path = rawurlencode($selfpage);
//Encode the Query String in the url.
$query_string_1 = '?find=' .urlencode($find) .'&table=' .urlencode($table) .'&column=' .urlencode($column) .'&max=' .intval($max);

$i = '1';
while($i<=$total_pages)
{
    $query_string_2 = '&page=' .intval($i);
    $url = $path .$query_string_1 .$query_string_2; //Full URL With $_REQUEST params (Query Strings): https://localhost/Templates/url_encode_Template.php?find=keyword&tbl=links&col=keyword&max=100&page=1

if($page == $i)
{
    //Bold the current Page numbered link.
    echo '<a href=' .'"' .$url .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>';
}
else
{
    echo '<a href=' .'"' .$url .'"' .'>' .intval($i) .'</a>';
}
$i++;
}

编辑 2: 更新 2: 根据 Magnus Eriksson 的旁注反馈,如果 mysql 连接失败,我将停止脚本。

if(!$conn = mysqli_connect("$server","$database"))
{
    echo 'Mysqli Connection Error' .mysqli_connect_error($conn);
    echo 'Mysqli Connection Error Number' .mysqli_connect_errno($conn);
die;
}

编辑 3: 更新 3: Magnus Eriksson 告诉我: “在同一个 if 中同时使用 isset() && !empty() 是没有意义的。只使用 !empty() 就足够了。“。 所以这些似乎毫无意义: 1.

if(ISSET($_REQUEST['table']) && !empty(trim($_REQUEST['table'])) && is_string(trim($_REQUEST['table'])))
if(ISSET($_REQUEST['column']) && !empty(trim($_REQUEST['column'])) && is_string(trim($_REQUEST['column'])))
if(!ISSET($_REQUEST['find']) || empty(trim($_REQUEST['find'])) && !is_string(trim($_REQUEST['find'])) || !is_int(trim($_REQUEST['find']))) 

无论如何,这是我的更新......

1.

if(!empty(trim($_REQUEST['table'])) && is_string(trim($_REQUEST['table'])))
if(!empty(trim($_REQUEST['column'])) && is_string(trim($_REQUEST['column'])))
if(empty(trim($_REQUEST['find'])) && !is_string(trim($_REQUEST['find'])) || !is_int(trim($_REQUEST['find']))) 

解决方法

这些用法都不正确。 htmlentites()htmlspecialchars() 用于页面上显示的内容。要在 URL 中使用,请使用 urlencode()。但仅限于属性values,否则您将破坏您的网址。

例如:

$url = "https://example.com/page";
$url .= "?param1=" . urlencode($value1);
$url .= "&param2=" . urlencode($value2);

但最好不要自己发明轮子。 PHP 有一个内置函数可以为您执行此操作:

$params = array(
    'param1' => $value1,'param2' => $value2
);

$url = "https://example.com/page?" . http_build_query($params);

仔细观察您的具体情况,我会将其简化为如下所示:

$total_pages = ceil($row_count/$max);
$selfpage = basename(__FILE__);

$query_params = array(
    'find' => $find,'table' => $table,'column' => $column,'max' => $max
);

for ($i = 1; $i <= $total_pages; $i++) {
    $query_params['page'] = $i;
    $url = $selfpage . "?" . http_build_query($query_params);

    echo '<a href="' . $url . '">';

    if ($page == $i) {  // shouldn't this be $page_no?
        echo '<b>' . $i . '</b>';
    } else {
        echo $i;
    }

    echo '</a>';
}

演示:https://3v4l.org/NApjm

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-