WordPress 4.4.2 Theme= Meeta from WPZoom
I have created a custom template that contains an SQL query of a custom table of dogs. The query works fine via the WPDB Class and I can display the output data in an acceptable format.
Now in the same custom template I insert a php form to allow the user to enter search criteria.
The form displays ok but the query executes immediately without waiting for the user to hit submit, consequently I cannot enter any search criteria. What should I do to hold the query until the form has been submitted?
I have fiddled around with this for some time and many times if I introduce an error elsewhere display reverts to home page without displaying errors. Do I have to turn on error display or is this sent to a log somewhere.
<?php the_content(); ?>
//=================================
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// set variables to wildcard
$dog_name = "%";
?>
<h2>Chercher dans la base</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Dog_name: <input type="text" dog_name="dog_name" value="<?php echo $dog_name;?>">
<input type="submit" name="submit" value="Submit">
</form>
<?php
$dog_name = test_input($_POST["dog_name"]);
global $wpdb;
$query = "SELECT offspring.dog_name, offspring.sex, offspring.color, offspring.dob, offspring.cotation, offspring.titles, offspring.hd, offspring.titles, offspring.eyes, offspring.dna, offspring.born_in, offspring.prod_prop, sire.dog_name AS sire, dam.dog_name AS lice
FROM BP_dog AS offspring
JOIN BP_dog AS sire ON sire.dog_id = offspring.sire_id
JOIN BP_dog AS dam ON dam.dog_id = offspring.dam_id
ORDER BY dog_name";
word
$results = $wpdb->get_results($query);
$num_rows = $wpdb->num_rows;
print "Number of rows = $num_rows.<br>";
foreach ($wpdb->get_results($query)as $row) {
print $row->dog_name . "t";
print $row->sex . "t";
print $row->dob . "t";
print $row->color . "t";
print $row->cotation . "t";
print $row->titles . "t";
print $row->hd . "t";
print $row->eyes . "t";
print $row->dna . "t";
print $row->born_in . "<br>";
print "Sire = " . $row->sire . "t";
print "Lice = " . $row->lice . "<br>";
print $row->prod_prop . "<br><br>";
}
?>
The Query you have written will directly runs if the page is loaded/reloaded. Use isset to execute code only id you
$_POST
data.I also modified few things on the code :
word
” at line 46Change
input type="text" dog_name="dog_name"
toinput type="text" name="dog_name"
Removed
$dog_name = "%";
. Not sure why you are using thisI made a more “hands-on” query builder that gonna work with any custom form to any table.