[英]use arrayed checkbox values in php MySQL WHERE clause
我正在嘗試通過ajax將7個jquery復選框的值發送到php。 我試圖將值放在數組中並在ajax中序列化該數組。 最終,我想將復選框的值用作MySQL WHERE子句中的條件。 我的ajax成功完成,但是我不確定如何將值從php變量中提取出來並在MySQL SELECT語句的WHERE子句中使用它們。
謝謝!!!
碼:
我的HTML代碼:
<label for="prestage_select">Prestage</label>
<input type="checkbox" name="revenue_checkboxes[]" id="prestage_select" class="revenuechbxs" value="Prestage">
<label for="validation_select">Validation</label>
<input type="checkbox" name="revenue_checkboxes[]" id="validation_select" class="revenuechbxs" value="Validation">
<label for="scheduling_select">Scheduling</label>
<input type="checkbox" name="revenue_checkboxes[]" id="scheduling_select" class="revenuechbxs" value="Scheduling">
<label for="production_select">Production</label>
<input type="checkbox" name="revenue_checkboxes[]" id="production_select" class="revenuechbxs" value="Production">
<label for="needsBOL_select">Needs BOL</label>
<input type="checkbox" name="revenue_checkboxes[]" id="needsBOL_select" class="revenuechbxs" value="Needs BOL">
<label for="shpAcct2Close_select">Shipped: Account to Close</label>
<input type="checkbox" name="revenue_checkboxes[]" id="shpAcct2Close_select" class="revenuechbxs" value="Shipped: Acctg. To Close Out">
<label for="movedToComplete_select">Moved to Complete for Selected Period</label>
<input type="checkbox" name="revenue_checkboxes[]" id="movedToComplete_select" class="revenuechbxs" value="Complete">
我的Ajax代碼:
j("#create_submit").click(function(){
//This works perfectly as long but the dates don't get sent through, causing my WHERE clause to fail unless I remove the $revenuefrom and $revenueto parts of the WHERE clause...
j.ajax ({
method: 'POST',
url: "revenue_report.php",
data: j('#revenue_form').serializeArray(),
success: function( response ) {
j('#fieldset_ReportDiv').html(response);
}
});
//No longer works...
//send Revenue Data values to php using ajax.
// var revenuechbxarray = j('.revenuechbxs:checked').serializeArray();
var revenuefrom = j('#revenuefrom').val();
var revenueto = j('#revenueto').val();
j.ajax ({
method: 'POST',
url: "revenue_report.php",
data: { revenuefromtext: revenuefrom, revenuetotext: revenueto },
success: function( response ) {
j('#fieldset_ReportDiv').html(response);
}
});
// console.log(revenuechbxarray);
我的PHP代碼:
<?php
include('inc.php');
//Get date range.
$revenuefromajax=$_POST['revenuefromtext'];
$revenuetoajax=$_POST['revenuetotext'];
$revenuefromstring = strtotime($revenuefromajax);
$revenuetostring = strtotime($revenuetoajax);
$revenuefrom=date("Y-m-d", $revenuefromstring);
$revenueto=date("Y-m-d", $revenuetostring);
//Get selected Status Values.
if (isset($_POST['revenue_checkboxes'])) {
$revenue_check = $_POST['revenue_checkboxes'];
print_r($revenue_check);
}; //Correctly displays only the values of selected checkboxes.
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
//echo 'MySQL Connected successfully.'."<BR>";
$conn->select_db("some database name"); /////Database name has been changed for security reasons/////////
if(! $conn->select_db("some database name") ) {
echo 'Could not select database. '."<BR>";
}
// echo 'Successfully selected database. '."<BR>";
//Select Data and Display it in a table.
$sql = "SELECT invoices.id, invoices.orderdate, invoices.stagestatus, FORMAT(TRIM(LEADING '$' FROM invoices.totalprice), 2) AS totalprice, clients.company, lineitems.invoiceid, FORMAT((lineitems.width * lineitems.height) /144, 2 ) AS sqft, lineitems.quantity AS qty, FORMAT((invoices.totalprice / ((lineitems.width * lineitems.height) /144)), 2) as avgsqftrevenue, FORMAT((TRIM(LEADING '$' FROM invoices.totalprice) / lineitems.quantity), 2) AS avgunitrevenue
FROM clients
INNER JOIN invoices ON clients.id = invoices.clientid
INNER JOIN lineitems ON invoices.id = lineitems.invoiceid
WHERE invoices.orderdate BETWEEN '".$revenuefrom."' AND '".$revenueto."' AND invoices.stagestatus IN (' .
implode(',' array_map(function($revenue_check) {
return '" . $revenue_check . "';
})) . '
)
ORDER BY invoices.id DESC";
$result = $conn->query($sql);
echo "<table id='revenueReportA' align='center' class='report_DT'>
<tr>
<th>Customer</th>
<th>SG</th>
<th>Revenue</th>
<th>SQ FT</th>
<th>AVG Revenue Per SQ FT</th>
<th>Number of Units</th>
<th>AVG Revenue Per Unit</th>
</tr>";
if ($result = $conn->query($sql)) {
// fetch associative array
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" ."$". $row['totalprice'] . "</td>";
echo "<td>" . $row['sqft'] ." ". "ft<sup>2</sup>". "</td>";
echo "<td>" ."$". $row['avgsqftrevenue'] . "</td>";
echo "<td>" . $row['qty'] . "</td>";
echo "<td>" ."$". $row['avgunitrevenue'] . "</td>";
echo "</tr>";
}
echo "</table>";
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Free the result variable.
$result->free();
}
//Close the Database connection.
$conn->close();
?>
注意:我還包括了另一個ajax調用,分別是Revenueto和Revenuefrom date。 這次呼叫成功,並且我的表格根據這些日期正確顯示。 我只是無法從日期所在的同一頁面上獲取所選復選框的所有實際值。
一旦獲得這些值,我還將在WHERE語句中提出有關正確使用它們的任何建議。 每個復選框的值都與一個值選項invoices.stagestatus相匹配。
謝謝!
您可以通過ajax請求傳遞數組。 初始化為一個空數組,然后將每個選定復選框的值推入該數組(我已注釋了您的代碼以顯示在哪里進行更改):
//send Revenue Data values to php using ajax.
//var revenuechbxarray = j('.revenuechbxs:checked').val();
var revenuechbxarray = [];
j('.revenuechbxs:checked').each(function(){
revenuechbxarray.push(j(this).val());
});
我不知道是否有最優雅的方法。
提交時,您會看到以下內容:
Array ( [0] => Prestage [1] => Validation [2] => Scheduling )
請注意,未選中的元素不會發布。
在PHP方面,要檢查是否發布了復選框,請檢查其值是否在數組中:
if (in_array('Prestage', $revenue_check)){
// your stuff here
}
編輯:您還可以在下面查看@rdimouro自己的答案,他在此顯示其完整的現在可用的版本。
如您所料,在當前代碼中, 只有第一個復選框值會添加到傳遞給Ajax的數據中。
要簡單地掌握整個表單數據,您只能使用$('form').serialize()
,如以下代碼片段所示:
$(document).ready(function() { console.log($('form').serialize()); });
label, button { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <label> <input type="checkbox" name="revenue_checkboxes[]" value="Prestage" checked> Prestage </label> <label> <input type="checkbox" name="revenue_checkboxes[]" value="Validation" checked> Validation </label> <label> <input type="checkbox" name="revenue_checkboxes[]" value="Scheduling"> Scheduling </label> <label> <input type="checkbox" name="revenue_checkboxes[]" value="Production" checked>Production </label> <label> <input type="checkbox" name="revenue_checkboxes[]" value="Needs BOL">Needs BOL </label> <label> <input type="checkbox" name="revenue_checkboxes[]" value="Shipped: Acctg. To Close Out">Shipped: Account to Close </label> <label> <input type="checkbox" name="revenue_checkboxes[]" value="Complete">Moved to Complete for Selected Period </label> <label> Other data <input type="text" name="other-data" value="Some other data"> </label> </form>
您會看到,使用此獨特的語句,您可以獲得所有數據的相當完整的集合,因此您可以在Ajax調用中使用它,僅此而已:
j("#create_submit").click(function(){
//send Revenue Data values to php using ajax.
j.ajax ({
method: 'POST',
url: "revenue_report.php",
data: j('#yourFormId').serialize(),
success: function( response ) {
j('#fieldset_ReportDiv').html(response);
}
});
return false;
});
因此,在PHP中,您收到的$_POST
項與表單中存在的不同name
一樣多。 因此, $_POST['revenue_checkboxes']
將是一個數組( 僅包含選中的值 )。
順便說一句,請注意:在當前的PHP代碼中,您正在尋找$_POST['revenuechbx']
,這是正確的,因為這是您在Ajax調用的data{}
參數中直接命名的方式。 但是使用上面的代碼,您將獲得HTML name
屬性 。
現在,關於如何使用WHERE子句中的復選框值,您的問題尚不清楚,無法完全確定。
但是,如果invoices
中的stagestatus
列的可能值直接是HTML <input>
被引用為value
屬性的value
,那么這很簡單:
$sql = '
SELECT invoices.id, invoices.orderdate, invoices.stagestatus, ...
FROM clients
INNER JOIN invoices ON clients.id = invoices.clientid
INNER JOIN lineitems ON invoices.id = lineitems.invoiceid
WHERE invoices.orderdate BETWEEN '".$revenuefrom."' AND '".$revenueto."'
AND invoices stagestatus IN (' .
implode(',', array_map(function($item) {
return '"' . $item . '"';
}, $revenue_check)) . '
)
ORDER BY invoices.id DESC
';
在上方,我們使用array_map()
將引號引起來,然后將implode()
獲得以逗號分隔的列表,從而填充SQL IN()
子句。
這樣,將僅選擇具有已檢查狀態之一的發票。
這是適用於我的情況的完整答案。 謝謝cFreed的所有幫助和修改!!!!
我的密碼:
HTML:
<label for="prestage_select">Prestage</label>
<input type="checkbox" name="revenue_checkboxes[]" id="prestage_select" class="revenuechbxs" value="Prestage">
<label for="validation_select">Validation</label>
<input type="checkbox" name="revenue_checkboxes[]" id="validation_select" class="revenuechbxs" value="Validation">
<label for="scheduling_select">Scheduling</label>
<input type="checkbox" name="revenue_checkboxes[]" id="scheduling_select" class="revenuechbxs" value="Scheduling">
<label for="production_select">Production</label>
<input type="checkbox" name="revenue_checkboxes[]" id="production_select" class="revenuechbxs" value="Production">
<label for="needsBOL_select">Needs BOL</label>
<input type="checkbox" name="revenue_checkboxes[]" id="needsBOL_select" class="revenuechbxs" value="Needs BOL">
<label for="shpAcct2Close_select">Shipped: Account to Close</label>
<input type="checkbox" name="revenue_checkboxes[]" id="shpAcct2Close_select" class="revenuechbxs" value="Shipped: Acctg. To Close Out">
<label for="movedToComplete_select">Moved to Complete for Selected Period</label>
<input type="checkbox" name="revenue_checkboxes[]" id="movedToComplete_select" class="revenuechbxs" value="Complete">
AJAX:
j("#create_submit").click(function(){
//send Revenue Data values to php using ajax.
j.ajax ({
method: 'POST',
url: "revenue_report.php",
data: j('#revenue_form').serializeArray(),
success: function( response ) {
j('#fieldset_ReportDiv').html(response);
}
});
//Remove Criteria selection fields.
j("#fieldset_2").remove();
j("#fieldset_3").remove();
j("#fieldset_4").remove();
j("#fieldset_5").remove();
j("#fieldset_6").remove();
j("#fieldset_7").remove();
j("#createDiv").remove();
//Show selected tables.
j("#revenueDT").show();
j("#revenueReport").css({"visibility":"visible", "display":"block"});
j("#ontimeReport").css({"visibility":"visible", "display":"block"});
j("#rejectReport").css({"visibility":"visible", "display":"block"});
j("#scheduleReport").css({"visibility":"visible", "display":"block"});
j("#customReport").css({"visibility":"visible", "display":"block"});
});
return false;
PHP:
<?php
include('inc.php');
//Get date range.
$revenuefromajax=$_POST['revenuefrom'];
$revenuetoajax=$_POST['revenueto'];
$revenuefromstring = strtotime($revenuefromajax);
$revenuetostring = strtotime($revenuetoajax);
$revenuefrom=date("Y-m-d", $revenuefromstring);
$revenueto=date("Y-m-d", $revenuetostring);
//Get selected Status Values.
//$revenuecheckboxes=$_POST['revenuechbx'];
//echo $revenuecheckboxes;
//$revenuecheckboxes=var_dump($_POST['revenuechbx']);
if (isset($_POST['revenue_checkboxes'])) {
$revenue_check = $_POST['revenue_checkboxes'];
};
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
//echo 'MySQL Connected successfully.'."<BR>";
$conn->select_db("some_DB_name");
if(! $conn->select_db("some_DB_name") ) {
echo 'Could not select database. '.'<BR>';
}
// echo 'Successfully selected database. '."<BR>";
//Select Data and Display it in a table.
$sql = "SELECT invoices.id, invoices.orderdate, invoices.stagestatus, FORMAT(TRIM(LEADING '$' FROM invoices.totalprice), 2) AS totalprice, clients.company, lineitems.invoiceid, FORMAT((lineitems.width * lineitems.height) /144, 2 ) AS sqft, lineitems.quantity AS qty, FORMAT((invoices.totalprice / ((lineitems.width * lineitems.height) /144)), 2) as avgsqftrevenue, FORMAT((TRIM(LEADING '$' FROM invoices.totalprice) / lineitems.quantity), 2) AS avgunitrevenue
FROM clients
INNER JOIN invoices ON clients.id = invoices.clientid
INNER JOIN lineitems ON invoices.id = lineitems.invoiceid
WHERE invoices.orderdate BETWEEN '".$revenuefrom."' AND '".$revenueto."' AND invoices.stagestatus IN (". implode(',', array_map(function($item) {return '"' . $item . '"'; }, $revenue_check)) .")
ORDER BY invoices.id DESC";
//Display daterange and table.
echo 'Displaying results for: '.$revenuefrom.' to '.$revenueto.'. '.'<BR><BR><BR>';
$result = $conn->query($sql);
echo "<table id='revenueReportA' align='center' class='report_DT'>
<tr>
<th>Customer</th>
<th>Stage Status</th>
<th>SG</th>
<th>Revenue</th>
<th>SQ FT</th>
<th>AVG Revenue Per SQ FT</th>
<th>Number of Units</th>
<th>AVG Revenue Per Unit</th>
</tr>";
if ($result = $conn->query($sql)) {
// fetch associative array
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['stagestatus'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" ."$". $row['totalprice'] . "</td>";
echo "<td>" . $row['sqft'] ." ". "ft<sup>2</sup>". "</td>";
echo "<td>" ."$". $row['avgsqftrevenue'] . "</td>";
echo "<td>" . $row['qty'] . "</td>";
echo "<td>" ."$". $row['avgunitrevenue'] . "</td>";
echo "</tr>";
}
echo "</table>";
//Free the result variable.
$result->free();
}
//Close the Database connection.
$conn->close();
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.