I am trying to allow users to search a database and echo results, the thing is I want to search multiple tables. I know I can do SELECT * FROM x1, x2 but the rows are named something else so I cant
echo $row['username']
when the other row is username2. Maybe if its possible something like if($row == whatever), idk. Thanks for any help.
<?php
$search = $_POST['Srch'];
$host = "whatever";
$db = "whatever";
$user = "whatever";
$pwd = "whatever";
$link = mysqli_connect($host, $user, $pwd, $db);
$query = "SELECT * FROM users WHERE email LIKE '%$search%'";
$results = mysqli_query($link, $query);
if(isset($_POST['Srch'])) {
if(mysqli_num_rows($results) >= 0) {
while($row = mysqli_fetch_array($results)) {
echo "Username: " . $row['username'];
echo "Email: " . $row['email'];
}
}
}
?>
<body>
<form action="" method="POST">
<input type="Text" name="Srch">
<input type="Submit" name="Submit">
</form>
Edit: Found a way to do this. Something like this works:
function search1() {
// Search stuff here
}
function search2() {
// Search more stuff here
}
if(isset($_POST['Srch'])) {
search1();
search2();
}
If you want to search multiple tables you're going to have to join them somehow. Since you didn't post your table structure, I can only make assumptions on what you're trying to do, but the general syntax would be:
$query = "SELECT * FROM users u LEFT JOIN something s ON s.id = u.something_id WHERE u.email LIKE '%$search%'";
Then you can echo out the different columns that return. But again, this question needs more information for a better answer.
Hope this helps anyway!
Related
I seem to be running into this issue often, usually for checking to see if a $_GET['id'] actually exists in my database before running another query, related or not to the id being received.
If a record exists with the same id, then I show the HTML, e.g.:
if ($r) { #query was successful
$num = mysqli_num_rows($r);
if ($num == 1) {
?>
<form method="post">
...
<input type="submit" value="Submit" />
</form>
<?php
} else {
echo 'No records';
}
} else {
echo 'Query Failed';
}
mysqli_free_result($r);
The above works, but let's say that I want to perform another unrelated query between my opening/closing form tags; would it be proper to simply do something like this, which I would consider a nested query:
$q = "SELECT id FROM stuff WHERE id = $id";
$r = #mysqli_query($dbc, $q);
if ($r) { #query was successful
$num = mysqli_num_rows($r);
if ($num == 1) {
?>
<form method="post">
<?php
$q = "SELECT example FROM somewhere";
$r = #mysqli_query($dbc, $q);
if ($r) {
$num = mysqli_num_rows($r);
if ($num > 0) {
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo $row['example'];
}
}
} else {
echo 'Query failed';
}
?>
<input type="submit" value="Submit" />
</form>
<?php
} else {
echo 'No records';
}
} else {
echo 'Query Failed';
}
mysqli_free_result($r);
Or maybe create a boolean, like so:
$id_status = 0;
$q = "SELECT id FROM stuff WHERE id = $id";
$r = #mysqli_query($dbc, $q);
if ($r) { #query was successful
$num = mysqli_num_rows($r);
if ($num == 1) {
$id_status = 1;
}
}
mysqli_free_result($r);
if ($id_status) { #Run another query
...
}
I currently have a problem when it comes to requiring two separate query results for one task: (1) generating inputs from another table, (2) displaying the current values, (3) checking to see what input that has been generated matches the current value, e.g.:
$q = "SELECT id, food FROM restaurants";
$q = "SELECT favFood FROM people WHERE id = 1"; #favFood is equal to the id of food
...
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
?>
#generate all food from table, make favFood the current selected input
<input type="radio" name="yum" value="<?php echo $row['id']; ?>" />
<?php
}
So as you can see, I am having trouble when it comes to unrelated queries; the last example would probably work with a UNION or something, but i'd have a bunch of repeated rows displaying favFood, so it doesn't feel right, e.g.:
favFood | id | food
1 | 1 | Pizza
1 | 2 | Burgers
1 | 3 | Monkey Brains
Before I end this, I just want to say that I have made an attempt to use mysqli_multi_query, but I most likely did something wrong; i'm not even sure if it would work in this case, or what it does exactly.
Thanks!
If you want to check whether a record exists multiple times in your code, I suggest to create a function which returns a bool.
function record_exists($dbc, $q){
$state = false;
if($r = #mysqli_query($dbc, $q)){
if(mysqli_num_rows($r) == 1){
$state = true;
}
mysqli_free_result($r);
}
return $state;
}
$q = "SELECT id FROM stuff WHERE id = $id";
if(record_exists($dbc, $q)){
echo 'Yay, it exists';
}
Then if you want to SELECT some fields from a table but the filter depends on a value from another table, you could JOIN two tables in the query like so:
SELECT restaurants.id, restaurants.food
FROM restaurants
JOIN people ON restaurants.id = people.favFood
WHERE people.id = 1
Now you only SELECT the fields you want from table restaurants and filter them on a person id from the table people.
Two reasons why you've got such a problem
You are doing A LOT of useless stuff.
no one needs you "query failed" statement.
num rows check is also superfluous
most of the code you write is just repetitions
Like PHP users from the last century you are mixing database calls with HTML output. Now you see that the term "spaghetti code" was coined for a reason.
Your database related code rewritten with simple mysqli wrapper:
$rows = [];
$found = $db->getOne("SELECT id FROM stuff WHERE id = ?i", $id);
if ($found) {
$rows = $db->getAll("SELECT example FROM somewhere");
}
Now you can proceed to HTML output, either inline or (better) by including a template
?>
<?php if ($rows): ?>
<form method="post">
<?php foreach ($rows as $row): ?>
<?=$row['example']?>
<?php endforeach ?>
<input type="submit" value="Submit" />
</form>
<?php else: ?>
No records
<?php endif ?>
This question already exists:
PHP KEYWORD SEARCH ENGINE NO RESULTS [duplicate]
Closed 7 years ago.
I have a simple MySQL database keyword search that is functional. However results for the search are not being returned if the keywords are not in the same order as entered in the database. For example searching for "dog cat lion" will return a result, but searching for "dog lion cat" will return no results.
Any help on how to fix this issue would be greatly appreciated. Here is my code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Part Search</title>
</head>
<body>
<?php
$username = "xxxx";
$password = "xxxx";
$hostname = "localhost";
//connection to the database
mysql_connect($hostname, $username, $password);
mysql_select_db("wesco");
$search = mysql_real_escape_string(trim($_POST['searchterm']));
$find_parts = mysql_query("SELECT * FROM `parts` WHERE `keywords` LIKE '%$search%'");
while($row = mysql_fetch_assoc($find_parts))
{
$name = $row['name'];
echo "$name<br />";
}
?>
</body>
</html>
You could use something like this
$searchArray = explode(" ", $_POST['searchterm']);
$query = "";
foreach($searchArray as $val) {
$search = mysql_real_escape_string(trim($val));
if (!empty($query)) {
$query = $query . " OR "; // or AND, depends on what you want
}
$query = $query . "`keywords` LIKE '%$search%'";
}
if (!empty($query)) {
$find_parts = mysql_query("SELECT * FROM `parts` WHERE $query");
}
Also, you should stop using the mysql_* functions and start using the object oriented implementation of mysqli.
You need to order your Query.
if you have an auto_incremented Id you could go:
$find_parts = mysql_query("SELECT * FROM `parts` WHERE `keywords` LIKE '%$search%' ORDER BY row_id asc");
you can order by Name or really anything:
$find_parts = mysql_query("SELECT * FROM `parts` WHERE `keywords` LIKE '%$search%' ORDER BY name asc");
Two options:
use the build in mysql search functionality.
https://dev.mysql.com/doc/refman/5.6/en/innodb-fulltext-index.html
this is probably the better solution.
if you want to continue to use LIKE, then split the words as follows.
select *
from parts
where
(
keywords LIKE '%$word1%'
AND
keywords LIKE '%$word2%'
AND
keywords LIKE '%$word3%'
)
I am making an electronic health system related to patient diagnosing in PHP and MySQL. I have made following tables in database with the following records:
Illness(illness_id(PK), illness_code,illness_name)
Symptom(symptom_id, illness_id(FK),symptom_name ).
Now, what I would like to do is that, I will write name of symptom in search bar and after clicking button, related diseases should be output. Could you tell me SQL query that will output appropriate diseases please?
Please try this. After you retrieve the symptom value from the search bar into a variable, say symptom_name_provided_in_search_bar, you can use that value in the below query
select illness_name
from illness a, symptom b
where a.illness_id = b.illness_id
and b.symptom_name = :symptom_name_provided_in_search_bar
For this to work you should create only one table illness with 2 rows:
illnessName and illnessSymptom. Note: This will only work if the symptom is written exactly as in the database.
<?php
$host = 'yourmysqlhost';
$user = 'yourmysqluser';
$pass = 'yourmysqlpassword';
$db = 'yourmysqldatabase';
$symptom = $_POST['symptom'];
$connect = mysqli_connect($host, $user, $pass, $db);
$sanitizedSymptom = mysqli_real_escape_string($connect, $symptom);
$query = mysqli_query($connect, "SELECT * FROM illness WHERE illnessSymptom = '".$sanitizedSymptom."'");
if(mysqli_num_rows($query) == 0)
{
echo '<p>No results...</p>';
}
else
{
while($row = mysqli_fetch_assoc($query))
{
echo '<h1>'.$row['illnessName'].'</h1>';
echo '<p>Symptom: '.$row['illnessSymptom'].'</p>';
echo '<br>';
}
}
?>
Edit:
To find a symptom that is approximately like the symptom in the database, the query should be like this:
$query = mysqli_query($connect, "SELECT * FROM illness WHERE illnessSymptom LIKE '%".$sanitizedSymptom."%'");
I have a MySql DB and in the Table 'Klant' I have the column names:
ID
Naam
Email
Soort
Status
I get the column names with this query:
$strSQL = "select column_name from information_schema.columns where table_name='Klant'";
And I am selecting the data from the Table with this simple query:
$strSQL1 = "SELECT * FROM NAW.Klant";
What I want to do is search a text and with str_replace I want to replace the column_names with the data from the DB. For example:
If I type in Hello Naam, your email adress is Email I would want it to display Hello Robert your email adress is robert#gmail.com. And I will put that in a loop to do it for every row. I am currently using this:
$ID = $row['Klant_ID'];
$Naam = $row['Naam'];
$Email = $row['Email'];
$Soort = $row['Soort'];
$Naam = $row['Status'];
$vaaw = array("[ID]","[Naam]", "[Email]", "[Soort]", "[Status]");
$vervang = array("$ID","$Naam", "$Email", "$Soort", "$Status");
echo str_replace($vaaw, $vervang, $message);
The reason I do not want to use this anymore is because if I ever need to change/add/delete a column the code would still work. (I know it is a bad idea to change columns but you never know.) And also this code will work with other Tables/DB's to.
I have tried loads of things to get this to work but I just haven't got a clue how to do this and it has been bugging me for almost 2 days now. If someone knows a function or a way to do this it would be very helpful!
Try this:
<?php
$strSQL = "select column_name from information_schema.columns where table_name='Klant'";
$con=mysqli_connect('host', 'username', 'password', 'db');
if(!$con){
//error
}
$result=mysqli_query($con,$strSQL);
if(!$result){
//error
}
$table_columns=array();
//$row=mysqli_fetch_assoc($result);
while($row=mysqli_fetch_assoc($result))
{
$table_columns[]=$row['column_name'];
}
$query="select * from NAW.Klant "; //limit 10";
$result=mysqli_query($con,$query);
if(!$result){
//error
}
$greeting_text="";
while($row=mysqli_fetch_assoc($result)){
$greeting_text.= (isset($row['naam']))? "Hello {$row['naam']}":""; // because you want the 'hello'
for($i=1;$i< count($table_columns);$i++){
$greeting_text.=" Your ".$table_columns[$i]." is ".$row[$table_columns[$i]].", ";
}
$greeting_text.="\n";
}
echo $greeting_text; //test your result
If you have a predefined string template (to be replaced by column names or their values), you need to change that code when there is any change in the table columns. I simply choose to dynamically generate the string depending on the availability of columns. But if you need to use a predefined string, it is not difficult to do so.
I solved it using the script that HamZa linked in the comments. Since he is not posting it as an answer I will do it myself because I think it could help others.
The code that solved the problem is this:
$connection = mysql_connect('localhost', 'root', 'pw') or die('couldn\'t connect to the database.<br>'. mysql_error());
mysql_select_db("NAW");
$strSQL1 = "SELECT * FROM Klant";
$result = mysql_query($strSQL1, $connection) or die('Something went wrong with the query.<br>'. mysql_error());
while($row = mysql_fetch_assoc($result)){
$text = $_POST['naam'];
foreach($row as $k => $v){
$text = str_replace('['.$k.']', $v, $text);
}
echo $text;
echo "<br>";
}
I am trying to display some rows from a database table based on choices submitted by the user. Here is my form code
<form action="choice.php" method="POST" >
<input type="checkbox" name="variable[]" value="Apple">Apple
<input type="checkbox" name="variable[]" value="Banana">Banana
<input type="checkbox" name="variable[]" value="Orange">Orange
<input type="checkbox" name="variable[]" value="Melon">Melon
<input type="checkbox" name="variable[]" value="Blackberry">Blackberry
From what I understand I am placing the values of these into an array called variable.
Two of my columns are called receipe name and ingredients(each field under ingredients can store a number of fruits). What I would like to do is, if a number of checkboxes are selected then the receipe name/s is displayed.
Here is my php code.
<?php
// Make a MySQL Connection
mysql_connect("localhost", "*****", "*****") or die(mysql_error());
mysql_select_db("****") or die(mysql_error());
$variable=$_POST['variable'];
foreach ($variable as $variablename)
{
echo "$variablename is checked";
}
$query = "SELECT receipename FROM fruit WHERE $variable like ingredients";
$row = mysql_fetch_assoc($result);
foreach ($_POST['variabble'] as $ingredients)
echo $row[$ingredients] . '<br/>';
?>
I am very new to php and just wish to display the data, I do not need to perform any actions on it. I have tried many select statements but I cannot get any results to display. My db connection is fine and it does print out what variables are checked.
Many thanks in advance.
EDIT:
Thanks a million for replying. However, I tried correcting my own code=blank page and both solutions above ==blank pages also. Grrrr!! Here is one solution I tried.
<?php
// Make a MySQL Connection
mysql_connect("localhost", "", "") or die(mysql_error());
mysql_select_db("") or die(mysql_error());
$query = "SELECT receipename FROM fruit ";
$cond = "";
foreach($variable as $varname)$cond .= " $varname like 'ingredients' OR";
$cond = substr_replace($cond, '', -2);
$query .= " WHERE $cond";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
echo $row['receipename'],'<br />';
}
I also tried
<?php
// Make a MySQL Connection
mysql_connect("localhost", "24056", "project99") or die(mysql_error());
mysql_select_db("24056db2") or die(mysql_error());
$variable=$_POST['variable'];
foreach ($variable as $variablename)
{
$query = "SELECT receipename FROM horse WHERE ingredients = '".$variablename."'";
while($row = mysql_fetch_assoc($query))
{
echo $row['receipename']."<br/>";
}
}
?>
I suppose another way to say it, if the checkbox variable is equal to a record under the ingredients column, I wish to print out the receipename of that record.
Im nearly getting confused here mysellf, haha.
Any other ideas I could try???
Correction in ur code
$query = "SELECT receipename FROM fruit WHERE $variable like ingredients";
$row = mysql_fetch_assoc($result);
Do u see the difference above?
Place "$query" in place of "$result" mysql_fetch_assoc($result)
My Solution
$variable=$_POST['variable'];
foreach ($variable as $variablename)
{
$query = "SELECT receipename FROM fruit WHERE ingredients = '".$variablename."'";
while($row = mysql_fetch_assoc($query))
{
echo $row['receipename']."<br/>";
}
}
Your question is not clear to me, you may try the following-
$query = "SELECT receipename FROM fruit ";
$cond = "";
foreach($variable as $varname)$cond .= " $varname like 'ingredients' OR";
$cond = substr_replace($cond, '', -2);
$query .= " WHERE $cond";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
echo $row['receipename'],'<br />';
}
NOTE: This code is not tested