【问题标题】:Validating Form Field against MYSQL database with PHP使用 PHP 验证针对 MYSQL 数据库的表单字段
【发布时间】:2014-03-12 19:59:07
【问题描述】:

我正在尝试做我认为是一项简单的任务,但结果却相当困难。我要做的就是提供一个 1 字段表单,允许用户输入一个唯一的 id 并点击提交。如果唯一 id 与数据库中的其中一个 id 匹配,那么它们将被定向到页面。如果 id 不匹配,我希望它告诉“Id 不匹配,再试一次”或类似的东西。

我看过无数涉及登录表单的教程,但这比我需要的要多一些,每次我尝试将其简化为我需要的内容时,它都不起作用。我尝试了很多不同的代码。这是我目前拥有的。

更新代码:

<form name="enterclient" method="post">
<label for="clientid">Enter your client id</label><br />
<input name="clientid" id="clientid"><br /><br />
<input type="submit" value="Submit" name="submit" id="submit">
</form>

<?php global $current_user;
  get_currentuserinfo();
$host = 'myhost';
$username = 'myuser';
$pass = 'mypass';
$database = 'mydb';
$link = mysqli_connect($host,$username,$pass, $database);

$clientid = $_REQUEST['clientid'];

if ($link) {

    if(isset($_POST['submit'])) {   
    if (empty ($clientid)) {
    //if username field is empty echo below statement
        echo "you must enter your unique username <br />";
    }
    $query = "SELECT * FROM wp_locations WHERE client = '". mysqli_real_escape_string($link,$clientid) ."'" ;
    $result = mysqli_query($link, $query) or die("Unable to query");
    $option = "";
    while($row=mysqli_fetch_array($result, MYSQLI_BOTH)) {
    $option .= "<option value='{$row['client']}'>{$row['client']}</option>";
    }
}

else {   
}//close else

if ($result) {
print $option;
    echo "query successful";
    header('location: http://www.google.com');
}
else {
    echo"query fail";
}


}//end of initial if $db_found

else {
    print "Database NOT Found ";
}

// disconnect from the database
mysql_close();?>

更新的输出: 当我到达初始页面时,它仍然显示“查询失败”,我猜这是因为 $clientid 还没有值。

当我在框中输入任何内容时,它都会返回“查询成功”。我希望它仅在输入与数据库值之一匹配时才返回成功。

如果我输入一个我知道与数据库值匹配的值,它会给我一个该数据库值的列表,无论它存在多少次,并说查询成功。

请务必注意,重定向似乎永远不会起作用。

【问题讨论】:

  • 你正在混合 mysql 和 mysqli
  • 你有 mysql_connect($host,$username,$pass);后来使用 $result = mysqli_query($query);所以查询不起作用你需要检查in1.php.net/mysqli_connect
  • 使用mysqli_*可以使用if(mysqli_num_rows($query) &gt; 0)来检查匹配;并且不要混合你的 SQL 函数,它们基本上不会混合 ;-) mysqli_*mysql_* 是一个致命的组合
  • 请在问题中发布您更新的代码。
  • 你没有把 all => mysql_ 改成 mysqli_

标签: php mysql sql database forms


【解决方案1】:

缩进后看看你的代码:

if ($db_found) {
    if(isset($_POST['submit'])) {
        //if username field is empty echo below statement
        if (empty ($clientid)){
            echo "you must enter your unique username <br />";
        }
    } else {   
        $query = "SELECT * FROM wp_locations WHERE client = '". mysqli_real_escape_string($clientid) ."'" ;
        $result = mysqli_query($query) or die("Unable to query");
        $option = "";
        while($row=mysql_fetch_array($result)) {
            $option .= "<option value='{$row['client']}'>{$row['client']}</option>";
        }
    }
    if ($result){
        print $option;
        echo "query successfull";
        header('location: http://www.google.com');
    } else {
        echo"query fail";
    }
//end of initial if $db_found
} else {
    print "Database NOT Found ";
}

现在您可以很容易地看到,您只在未提交表单时才形成查询。我很确定这不是你想要的。是吗???

您希望类似于:

if ($db_found) {
    if(isset($_POST['submit'])) {
        //if username field is empty echo below statement
        if (empty ($clientid)){
            echo "you must enter your unique username <br />";
        }
        $query = "SELECT * FROM wp_locations WHERE client = '". mysqli_real_escape_string($clientid) ."'" ;
        $result = mysqli_query($query) or die("Unable to query");
        $option = "";
        while($row=mysql_fetch_array($result)) {
            $option .= "<option value='{$row['client']}'>{$row['client']}</option>";
        }
        if ($result){
            print $option;
            echo "query successfull";
            header('location: http://www.google.com');
        } else {
            echo"query fail";
        }
    }
//end of initial if $db_found
} else {
    print "Database NOT Found ";
}

但是您仍然有使用 mysql_*mysqli_* 混合使用的问题 扩展只使用 mysqli_* 然后您需要查看函数以使用正确的参数,例如 mysqi_query 现在采用最少两个参数。看看这些参考资料:

解决方案: 下面应该是我尚未测试此代码的工作解决方案,但它应该是您正在寻找的。通常我不会到这种程度来做别人的工作,但今天早上我感到很慷慨。

<form name="enterclient" method="post">
<label for="clientid">Enter your client id</label><br />
<input name="clientid" id="clientid"><br /><br />
<input type="submit" value="Submit" name="submit" id="submit">
</form>

<?php

global $current_user;
get_currentuserinfo();
$host = 'myhost';
$username = 'myuser';
$pass = 'mypass';
$database = 'mydb';
//connect to MySQL database
$link = mysqli_connect($host,$username,$pass, $database);
//if not connected kill page and throw error
if (!$link) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}
//check if form submitted and clientid is not empty
if(isset($_POST['clientid']) && !empty($_POST["clientid"]))){
    //escape clientid to use in query
    $clientid = mysqli_real_escape_string($link,$_POST['clientid']);
    //form query
    $query = "SELECT client FROM wp_locations WHERE client = '$clientid'";
    //run query on server and if not successful then kill page and throw error
    $result = mysqli_query($link, $query) or die(mysqli_error($link));
    //set variable to fill with database data and print
    $option = "";
    //check if any rows were returned from database
    if(mysqli_num_rows($result)>0){
        //for each row that was returned set $row equal to an array of values for that row
        while($row=mysqli_fetch_array($result)) {
            //set $option with values from the database as there is only possible one value use = instead of .=
            $option = "<option value='{$row['client']}'>{$row['client']}</option>";
        }
        //print the option
        print $option;
        //show that the query was successful
        print "query successful";
        //set redirect to happen in 5 seconds
        $redirect = "http://www.google.com";
        $wait = 5; // seconds to wait
        print "You will be redirected to $redirect in $wait seconds."
        print "<span style='display:none'><meta http-equiv='Refresh' content='$wait; URL=$redirect'></span>";
    } else {
        //show that the query was successful but that the client was not found
        print "query successful but client not found please try again";
    }
    //free the MySQL result set
    mysqli_free_result($result);
} else {
    //the form was either not submitted or submitted with an empty value.
    print "Please complete and submit the form above.";
}
//close the connection to the MySQL server
mysqli_close($link);

?>

【讨论】:

  • 我查看了您的建议并尝试实施它们。我已经用我正在使用的新代码更新了这个问题。现在,当我转到该页面时,它最初显示“查询失败”,然后当我在框中键入任何内容并单击提交时,它返回“无法查询”。想法?
  • 问题中的当前代码似乎是临界功能。剩下的唯一问题是,即使输入的值与数据库值不匹配,并且重定向也无法正常工作,它也会使查询成功。
  • 你的query successfull返回检查mysqli_query的返回看看这里的参考:us2.php.net/mysqli_query你应该使用mysqli_num_rows检查是否返回了任何行。至于重定向,您需要阅读标头函数:us2.php.net/manual/en/function.header.php 特别是Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. 在调试时应该经常使用引用,这样您就会明白为什么重定向不起作用。
  • 您能举个例子说明如何实现 mysqli_num_rows 片段吗?
  • 我觉得问题出在包含 $result 的 if 语句中。我想做的是说,如果(输入的值=来自数据库的客户端值)然后运行该函数。如果它不匹配 else{ echo "failed"} 知道我可以更改 if 语句以使其工作吗?
猜你喜欢
  • 2014-10-21
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 2014-05-08
  • 2012-04-07
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
相关资源
最近更新 更多