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条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥100 支付宝网页转账系统不识别账号