wordpress query select code example
Example 1: wp do sql query from function
<?php
// 1st Method - Declaring $wpdb as global and using it to execute an SQL query statement that returns a PHP object
global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT );
Example 2: wp do sql query from function
<?php
// 2nd Method - Utilizing the $GLOBALS superglobal. Does not require global keyword ( but may not be best practice )
$results = $GLOBALS['wpdb']->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT );
Example 3: wordpress query to save in database
<?php
if (!empty($_POST)) {
global $wpdb;
$table = 'contact_form';
$data = array(
'names' => $_POST['yourname'],
'emails' => $_POST['customer_email'],
'gender' => $_POST['customer_gender'],
'age' => $_POST['customer_age']
);
//echo "<pre>"; print_r($data);
$success=$wpdb->insert( $table, $data );
if($success){
echo 'data has been save' ;
}
} else {
echo "data not save";
}
?>
<div class="container">
<div class="row ">
<div class="col-md-12 pb-5">
<form method="post">
Your name:<input type="text" name="yourname" id="yourname">
Your Email:<input type="text" id="customer_email" name="customer_email"/><br>
Gender:<input type="radio" name="customer_gender" value="male">Male
<input type="radio" name="customer_gender" value="female">Female<br>
Your Age:<input type="text" name="customer_age" id="customer_age"><br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
</div>
</div>