2017-12-29 7 views
0

PHP에서 페이지를 다시로드 할 때 어떻게 값을 입력에서 SQL 문에 추가 할 수 있습니까?

<div> 
    <label>From</label> 
    <input type=date name=from value="12-12-2017"> 
    <label>To</label> 
    <input type=date name=to value="29-12-2017"> 
</div> 


$query = $conn->prepare("SELECT * FROM Users WHERE age BETWEEN **From** and **To**") 
$query->execute() 

예 그리고 어떻게 입력에서 값을 페이지 처음으로 다시로드 할 때 SQL 문에 추가 할 수 있습니까? 미리 감사드립니다.

+0

날짜를 varchar로 저장하지 않습니다. –

답변

1

이것은 처음에만 제출하는 코드 예제입니다.

PHP/MySQLi 태그가 붙어 있기 때문에 날짜 입력이 끝나면 버튼을 눌러야하는 예제가 있습니다.

<?php 
// session_start() has to be the first line of code 
session_start(); 

$con = new mysqli($servername, $username, $password, $dbname); 

// if there is NOT a valid POST request (means it is like a first visit) 
if (!$_POST) 
{ 
    // if the session variable is set unset it 
    if(isset($_SESSION['beenHere'])) unset($_SESSION['beenHere']); 

    echo 'Status: This is a fresh start.<br/>'; 
} 
else if(isset($_POST['from']) && isset($_POST['to']) && 
    !empty($_POST['from']) && !empty($_POST['to']) && 
    !isset($_SESSION['beenHere'])) 
{ 
    // set the session variable to an arbitrary value, it's important it is set 
    $_SESSION['beenHere'] = 'This is the first submit'; 
    // prepare the statement 
    $stmt = $con->prepare("SELECT * FROM Users WHERE age > ? AND age < ?"); 
    // turn the input variables into proper date format and bind the to the ? 
    // dates are considered strings in prepared statements 
    $stmt->bind_param("ss", date('Y-m-d',strtotime($_POST['from'])), date('Y-m-d',strtotime($_POST['to']))); 
    $stmt->execute(); 

    // Here you list all the output columns that you have. I only listed two example columns. 
    $stmt->bind_result($name, $age); 
    // loop for each returned row 
    while ($stmt->fetch()) 
    { 
     // print the results 
     printf ("%s %s\n", $name, $age); 
    } 
} 
?> 

<!-- Leave the action empty to POST to self --> 
<form action="" method="POST"> 
    <div> 
    <label>From</label><input type="date" name="from" value="" /> 
    <label>To</label><input type="date" name="to" value="" /> 
    </div> 
    <input type="submit" value="clickToEnter" /> 
</form> 

참고 : 고급 예를 들어 당신이 javascript/jQuery에 의존 할 수는 세션 변수 클라이언트 측을 설정할 수 있습니다. 그렇다면 POST을 쓸 필요가 없습니다. $_SESSION에 중요한 정보를 저장하고 페이지로드를 확인할 수 있기 때문입니다.

관련 문제