Reputation: 113
i have 4 variable like this :
$a = $_POST['a']; //1
$b = $_POST['b']; //
$c = $_POST['c']; //
$d = $_POST['d']; // 5
currently mysql work that catch all value from input:
$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key IN(rate1,rate2,rate3,rate4) AND post_id=".$_POST['postid']);
$wpdb->query( "INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value) VALUES ($_POST['postid'],rate1,$a),($_POST['postid'],rate2,$b),($_POST['postid'],rate3,$c),($_POST['postid'],rate4,$d) ");
Is there anyway that reduce query that only insert/delete when $_POST not null . Current i check if $_POST not null , i will run delete/insert once . It make my code very long because i must check both a,b,c,d then insert/delete
if($a != ""){
$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key=rate1 AND post_id=".$_POST['postid']);
$wpdb->query( "INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value) VALUES ($_POST['postid'],rate1,$a) ");
}
Upvotes: 0
Views: 390
Reputation: 1863
According to your original code, PHP will throw a notice if any of the four variables isn't set (you're trying to access an array index that doesn't exist).
To conform to the fail-fast
principle, you'd want to elevate that notice to the status of an exception, by having the following code somewhere high in the hierarchy (PHP7+ code, but PHP5+ code is available in the bottom link).
set_error_handler(function($severity, $message, $filename, $lineno) {
throw new Exception($message);
});
This way, whenever you're trying to read a POST variable that hasn't been set, execution won't move forward with incomplete data. You will need to do a try/catch to gracefully handle that exception.
PHP5+ code: https://www.electrictoolbox.com/error-reporting-exception-handlers-php/
Upvotes: 0
Reputation: 262
<?php
$errors = false;
$fields = array("a","b","c","d");
foreach($fields as $fieldname){
if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])){
$errors = true;
echo "enter ".$_POST[$fieldname];
}
}
if(!$errors){
$a = $_POST['a']; //1
$b = $_POST['b']; //
$c = $_POST['c']; //
$d = $_POST['d']; // 5
// DO your queries
}
?>
Take care of the sql injections
Upvotes: 1
Reputation: 89
It looks like it may be sth that you are looking for:
if (isset($_POST)){
//code here
}
Upvotes: 0