douyi1966 2013-05-27 23:20
浏览 39
已采纳

PHP停止运行脚本

I wrote this script where you go to localhost/censor.php/query and it sees if it is taken. Here is the code:

<?php
function curPageURL() {
    $pageURL = 'http';
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80")
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    else
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];

    return $pageURL;
}

$test = curPageURL();
$test = str_replace('http://localhost/censor.php/',"",$test);

$con = mysqli_connect("localhost","root","creepers2","spider");

if (mysqli_connect_errno())
    echo "Failed to connect to MySQL: " . mysqli_connect_error();

$usname = null;
$result = mysqli_query($con, "SELECT * FROM main WHERE urls='$test'");
while($row = mysqli_fetch_array($result) or die(mysqli_error($con))) {
    $usname = $row['urls'];
    if ($usname=$test)
        echo "Taken!";
    else
        echo"YEAH!";
}

mysqli_close($con);
?>

If you to localhost/censor.php/queryinthedatabase it prints out taken. However, if you go to localhost/censor.php/querynotinthedatabase, it prints nothing. Help please?

  • 写回答

3条回答 默认 最新

  • drurhg37071 2013-05-27 23:29
    关注

    You are doing a simple query: SELECT * FROM main WHERE urls='$test'. That's fine (SQL injections aside).

    Now, you're fetching all results and looping through them by using while($row = mysqli_fetch_array($result) or die(mysqli_error($con))). That said, if there were no results, it won't loop through any objects as it can't fetch any.

    You should use something like mysqli_num_rows. For example:

    $result = mysqli_query($con, "SELECT * FROM main WHERE urls='" . mysqli_real_escape_string($test) . "'");
    if (mysqli_num_rows($result) == 1) {
        echo "Taken!";
    }
    else {
        echo "YEAH!";
    }
    

    Now you're doing the same query (selecting all rows where urls is equal to $test), but instead of looping through the returned rows, you count the amount of rows that the query returned. If it equals 1, it's taken.

    Also, please escape any user-input you put into your queries; don't get to be yet another victim of SQL injections. Never trust the user!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常