2014-03-12 2 views
0

간단한 작업 일 것이라고 생각하지만 실제로는 어렵다고 판명되었습니다. 내가 원하는 것은 1 개의 필드 형식을 제공하여 사용자가 고유 한 ID를 입력하고 제출을 허용하는 것입니다. 고유 ID가 데이터베이스의 ID 중 하나와 일치하면 페이지로 연결됩니다. ID가 일치하지 않으면 "Id does not match, again try"또는 그와 비슷한 것을 말하고 싶습니다.PHP를 사용하여 MYSQL 데이터베이스에 대해 양식 필드 유효성 검사

로그인 양식이 포함 된 수많은 자습서를 살펴 보았습니다.하지만 필요한 것보다 조금 더 많은 것입니다. 필요한만큼 단순화하려고 할 때마다 작동하지 않습니다. 나는 다른 코드 톤을 시도했다. 여기 제가 현재 가지고있는 것이 있습니다.

업데이트 된 코드 :

<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();?> 

업데이트] OUTPUT : 나는 초기 페이지에 도착, 그것은 여전히 ​​'쿼리 실패 "와 나는 $의 된 ClientID 나던 아직 값이 때문입니다 추측하고 말한다 .

상자에 내용을 입력 할 때 "query successful"이 반환됩니다. 입력이 데이터베이스 값 중 하나와 일치하는 경우에만 성공적으로 리턴하고 싶습니다.

내가 데이터베이스 값과 일치하는 값을 입력하면 데이터베이스 값 목록이 여러 번 존재하지만 쿼리 성공이라고 표시됩니다.

리디렉션이 작동하지 않는 것처럼 보일 수 있습니다. 이 들여 쓰기 한 후 코드에서

+0

mysqli와 함께 mysqli을 혼합 할 경우 –

+0

을 구체적으로 지정할 수 있습니까? – Chris

+1

당신은 mysql_connect ($ 호스트, $ 사용자 이름, $ 패스); 그리고 나중에 $ result = mysqli_query ($ query); 그래서 쿼리가 작동하지 않습니다. http : //in1.php를 확인해야합니다.net/mysqli_connect –

답변

0

봐 :

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 "; 
} 

하지만 당신은 여전히 ​​mysqli_* 확장과 혼합 mysql_*을 사용하는 문제가mysqli_* 당신이 다음 현재 인스턴스 mysqi_query에 대한 올바른 매개 변수를 사용하는 함수에서 볼 필요가 사용 최소 두 개의 매개 변수를 취합니다. 이러한 참조를 보라 :

해결책 : 아래이 코드를 테스트하지 않은 작업 솔루션을해야하지만, 당신이 무엇을해야 를 찾고 있습니다. 일반적으로 나는이 정도까지 누군가 elses의 일을하기 위해 가지 않는다. 그러나 나는 오늘 아침 관대하게 느꼈다.

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

?> 
+0

제안을보고이를 구현하려고 시도했습니다. 내가 사용하고있는 새로운 코드로 질문을 업데이트했다. 이제 내가 처음에 "쿼리 실패"라고 말한 다음 상자에 아무 것도 입력하고 제출을 클릭하면 "쿼리 할 수 ​​없습니다"라는 결과가 반환되는 페이지로 이동합니다. 생각? – Chris

+0

질문의 현재 코드가 경계선 기능을하는 것처럼 보입니다. 유일한 문제는 입력 값이 데이터베이스 값과 일치하지 않고 리디렉션이 작동하지 않는 경우에도 쿼리 성공을 제공한다는 것입니다. – Chris

+0

'mysqli_query'의 리턴을 체크했을 때'query successfull'이 반환하는 참조는 http://us2.php.net/mysqli_query입니다. mysqli_num_rows를 사용하여 리턴 된 행이 있는지 확인해야합니다. 리다이렉트까지 헤더 함수를 읽어야한다 : http://us2.php.net/manual/en/function.header.php 특히'실제 출력이 나오기 전에 header()가 호출되어야한다는 것을 기억하라. 보통 HTML 태그, 파일의 빈 줄 또는 PHP에서 보내집니다. 디버깅 할 때 자주 참조를 사용하여 리디렉션이 작동하지 않는 이유를 확인해야합니다. – amaster

관련 문제