如果WordPress数据库表中不存在该值,则输入框边框为红色



我想从所有文本框向我的WordPress MySQL数据库表table1提交值。但在提交数据之前,如果match1match2match3等文本框值已存在于table2(列名ref_code(中,则文本框边框(或阴影(应分别变为绿色。如果table2(列名ref_code(中不存在值,则该特定match文本框的边框应变为红色。

请查看我当前的代码,并给我宝贵的建议。(给定的代码只是在table1中插入数据,但我想在table2列中搜索:ref_code(

<?php   
if (!empty($_POST)) {
global $wpdb;
$data = array(
'order_id' => $_POST['order_id'],
'raw_data'   => $_POST['raw_data']          
);  
for( $i=1; $i<6; $i++) :
$data['match'.$i] = $_POST['match'.$i];
$data['buy'.$i] = $_POST['buy'.$i];
$data['percent'.$i] = $_POST['percent'.$i];
endfor;     
$success=$wpdb->insert( 'test1', $data, $format=NULL );
if($success){
echo "=> DATA SAVED" ; 
?>
<form method="post">
<div class='mainIn'>Order ID<br>
<input type="text" name="order_id"></div>
<div class='mainIn'>Raw Data<br>
<textarea type="text" name="raw_data"></textarea></div>     
<br><br><div style='display:flex;flex-wrap:wrap'>
<?php for( $i=1; $i<6; $i++) : ?>
<div id='allpeaks' style='flex:0 0 100%'>
Match<?php echo $i;?><input class='inCol' name='match<?php echo $i;?>'>
Buy<?php echo $i;?><input class='inCol' name='buy<?php echo $i;?>'>
Percent<?php echo $i;?><input class='inCol' name='percent<?php echo $i;?>'>
</div><br><br>
<?php endfor;?>         
</div>      
<br><input type="submit">
</form>

除非使用ajax检查值是否存在,否则无法在php运行时之后呈现样式。

这里有一个html输入、Javascript Ajax和SQL查询的简单示例:

https://www.w3schools.com/php/php_ajax_php.asp

你可以用这样的东西。因此,在用户提交inputorder_id上的值之后,您可以使用ajax检查值是否存在。您需要一个php文件来检查它:

<?php // This is yourcheck.php
$order_id = $_GET["order_id"];
$exists = $wpdb->get_var("SELECT ref_code FROM $wpdb->table2 WHERE ref_code = $order_id");
// Here check if value already exists in table2
if($exists){
$response = array("exists" => true);
echo json_encode($response); 
} else {
// Here insert your data in table1
//...
$wpdb->insert( 'table1', $data, $format=NULL );
}
?>

根据您的输入,您需要包含以下脚本:

<script>
var order_id = document.getElementById("order_id").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Check if exists value in table2, if true change border color of input
if(this.exists){
document.getElementsByName("order_id")[0].style.borderColor = "red";
}
}
};
xmlhttp.open("GET", "test.com/yourcheck.php?order_id="+order_id, true);
xmlhttp.send();
</script>

<input type="text" name="order_id">

相关内容

最新更新