I'm making a spellcheck app with slang words. If the checkbox is checked, the code will search on both english_table and slang_table. otherwise it will only search on english_table.
i've tried using if statement but it seems wrong.
$sql = "SELECT * FROM english_table WHERE engwords LIKE '".$partcheck."'";
$sql1 = "SELECT * FROM slang_table WHERE words LIKE '".$partcheck."'";
if statement if checked
if($result = mysqli_query($con, $sql){...}
elseif($result = mysqli_query($con, $sql1){...}
my expectation is if the checkbox is checked the code will search for matching word from both tables, otherwise is will only search on english_table. How do I do this?
To merge results from 2 tables you should use the UNION operator in SQL. You can learn more about that here https://www.w3schools.com/sql/sql_union.asp
Resulting in this query:
SELECT * FROM english_table WHERE engwords LIKE 'XXXXXX'
UNION
SELECT * FROM slang_table WHERE words LIKE 'XXXXX'";
With this query, the tables should have similar columns in the same order. If you have different columns, consider specifying them instead of getting everything.
You can then conditionally add the second part of the query depending on your if statement.
PHP:
$sql = "SELECT * FROM english_table WHERE engwords LIKE 'XXXXXXX";
if ($checked) {
$sql .= " UNION SELECT * FROM slang_table WHERE words LIKE 'XXXXXXX'";
}
// closing the sql query
$sql .= ";";
However, as Dharman has said, your code is open to SQL injection and as it may not seem a problem now, as soon as the website goes up someone will try and successfully take control of your database. Follow his links to learn more about the current practices for dealing with database queries in PHP.
You could just run a Union ALL conditionally:
$likePartcheck = '%' . $partcheck . '%';
$query = "SELECT * from english_table WHERE engwords LIKE ?" . ($_GET['checkbox'] ? " UNION ALL SELECT * FROM slang_table WHERE words LIKE ?" : "");
$stmt = $mysqli->prepare($query);
if ($_GET['checkbox']) {
$stmt->bind_param('ss', $likePartcheck, $likePartcheck);
} else {
$stmt->bind_param('s', $likePartcheck);
}
$stmt->execute();
Or if you want the results separate just run two queries and combine the results as you see fit.