I've got a database that contains two tables, both tables are containing postcodes i.e. "SY25 6WB" I've built a query that will query the database for a postcode entered in a textbox, if the postcode is in the database, it does some jquery - all works fine,
what i'm aiming to do is, have the query run first based on postcode, then if that's not found, search the next table for the postcode IF the dropdown is populated with a certain value. I'm also looking for a way to ignore whitespace, so if a user was to enter "SY256WB" or "SY25 6WB" it would pull the same result.
I've pasted my code below.
Form:
<form action="" method="post">
Search: <input type="text" name="term" />
<select name="options">
<option value="YES">YES</option>
<option value="NO">NO</option>
</select>
<p>Enter your full postcode with spaces i.e. SA1 3XL</p>
<br />
<input type="submit" value="Submit" />
</form>
PHP
<?php
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$benefit = mysql_real_escape_string($_REQUEST['YES']);
$sql = "SELECT * FROM cscopc WHERE POSTCODE LIKE '".$term."'";
$r_query = mysql_query($sql);
if ( mysql_num_rows($r_query) > 0 ) {
echo 'YES';
}
else if ( mysql_num_rows($r_query) == 0 ) {
$sqltwo = "SELECT * FROM cscowb WHERE PCODE LIKE '".$term."'";
$nextab = mysql_query($sqltwo);
if ( mysql_num_rows($nextab) > 0 ) {
echo 'YES WITH OPTION';
}
else {
echo 'NO';
}
}
}
?>
If anyone could shed some light on how i could do this or point me in the right direction for some reference, it would be much appreciated!
UPDATED with new query using PDO:
try {
$conn = new PDO('mysql:host=localhost;dbname=cscoapp', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$id = $_POST['term'];
if (!empty($_REQUEST['term'])) {
$stmt = $conn->prepare('SELECT * FROM cscopc WHERE POSTCODE = :id');
$stmt->execute(array('id' => $id));
if ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
echo 'YEP';
}
else if ($_POST['benefits'] == 'yes') {
$stmtwb = $conn->prepare('SELECT * FROM cscowb WHERE POSTCODDE = :id');
$stmtwb->execute(array('id' => $id));
if ($row = $stmtwb->fetch(PDO::FETCH_OBJ)) {
echo 'YEP';
}
}
else {
echo 'nope';
}
}