Reputation: 51
I am trying to create a function that will check against the data from the database. If the results are empty, continue with the code. If else, abort.
Here is an example of my code.
function check_if_blocked(){
global $wpdb;
$user = '1';
$results = $wpdb->get_results("SELECT * FROM mytable WHERE user = $user");
if(empty($results)){
$var = false;
} else {
$var = true;
}
return $var;
}
Function check_if_blocked is going to be used multiple through out the plugin.
Here is an example of how I plan on using check_if_blocked()..
function msg_form(){
if(check_if_blocked(){
echo '<form action="" method="post">
<input type="text" name="msg">
<input type="submit" name="submit" value="send">';
}
}
Regardless on how I switch around the true, false, and even if(!check_if_blocked...
Upvotes: 0
Views: 8731
Reputation: 51
After everyone's advice. I finally got it to work. Here is my code.
function check_if_blocked($blocked){
global $wpdb;
$user = '1';
$user2 = '2';
$results = $wpdb->get_results("SELECT * FROM mytable WHERE blocked = $user AND blocker = $user2");
if(empty($results)){
$blocked = 'not_blocked';
} else {
$blocked = 'is_blocked';
}
}
function msg_form(){
if(check_if_blocked($blocked) == 'not_blocked){
echo '<form action="" method="post">
<input type="text" name="msg">
<input type="submit" name="submit" value="send"></form>';
}
}
Upvotes: 0
Reputation: 414
You are trying to return the wrong value, get_results will return true if the query was successful, not if it found matches, so, it might return true even if there are no matching records found, try this instead:
function check_if_blocked()
{
global $wpdb;
$user = '1';
$results = $wpdb->get_results("SELECT * FROM mytable WHERE user = $user");
if(!$results) {return false;} // query failed, no way to know if there are matching records.
$numrows = count($results); // query worked, now, check if there are matching records.
if (is_int($numrows) && $numrows) {$var = true;} else {$var = false;}
return $var; // return the result.
}
Now, the function will return true only if there are one or more matching records.
Also, you have a syntax error here:
if(check_if_blocked(){
It should be:
if(check_if_blocked()){
Upvotes: 1