Disease-Symptom relation in MySQL - php

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."%'");

Related

Is it possible to loop through each row of a table in a database

I'm trying to loop through each row of a table in a database, then once I'm on a particular row get the value of a certain column. Is this possible? I've done a couple Google searches but nothing really concrete. I try using the mysqli_fetch_array() function but when I do I get the results of a column. I want to target each row. The code I have so far gets me the "nid" column. That's not what I want. I want to iterate through each row.
<?php
$serverName = "localhost";
$username = "user1";
$password = "sp#99#1";
$databaseName = "developer_site";
// Connection
$connection = new mysqli($serverName, $username, $password, $databaseName);
// Check Connection
if ($connection->connect_error) {
die("Connection failed:" . $connection->connect_error);
} // line ends if statement
$queryNodeRevision = "SELECT nid FROM node_revision";
// line above creates variable $queryNodeRevision > selects column "nid" from table "node_revision"
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
echo "NID: ";
echo $row['nid'];
echo "<br/>";
}
?>
You can select rows by a certain condition with an SQL query alone and also select all columns.
SELECT * FROM node_revision where condition;
condition could be anything. For example another_row = 'something'.
But if, for some reason, you need to process the nid inside your php script to know if that row is the "particular" one you're searching, then you just select all the columns, or the ones you need.
$queryNodeRevision = "SELECT nid, col1, col2 FROM node_revision";
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
if (condiiton) {
echo "Particular: ".$row['nid']
." ".$row['col1']
." ".$row['col2'];
}
}
condition could be something like $row['nid'] == 123 for example.
Hope it helps.

PHP MySQL WHERE column-value is in $_POST

I'm trying to get all the rows which contain a particular text. However, when I execute the query, no rows are returned. I'm retrieving the text from a post request which looks like this "Krachttraining,Spinning" (= 2 values). I think my code fails on the following part (if I leave this out, the query returns some rows): AND CONCAT('%', sport.name, '%') LIKE $sports.
FYI. I know you can perform SQL injection on this, this will be fixed later.
<?php
$servername = "SECRET";
$username = "SECRET";
$dbpassword = "SECRET";
$dbname = "SECRET";
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$sports = $_POST['sports'];
echo $sports; //Echo's: Krachttraining,Spinning.
// Create connection.
$conn = new mysqli($servername, $username, $dbpassword, $dbname);
// Check connection.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT gym.id FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND CONCAT('%', sport.name, '%') LIKE $sports";
$result = $conn->query($sql);
$output = array();
if ($result->num_rows > 0) {
// output data of each row.
while($row = $result->fetch_assoc()) {
$id = $row["id"];
array_push($output, $gym);
}
//Brackets because of GSON's parser.
echo "[" . json_encode($output) . "]";
}
$conn->close();
?>
EDIT: Changed SQL statement to:
$sql = "SELECT * FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND sport.name LIKE '%".$sports."%'";
Still getting 0 rows returned.
EDIT 2: I ran the following code in my phpMyAdmin environment, and it returned 0 rows.
Select * FROM sport WHERE name LIKE '%Krachttraining,Spinning%';
However when I'm running the following code, it returns 1 row:
Select * FROM sport WHERE name LIKE '%Krachttraining%';
I don't really get it what I'm doing wrong, any thoughts?
I think you want to use the IN statement.
This will check if any word in the array matches. For instance:
Select * FROM sport WHERE name IN ('Spinning', 'Krachttraining'); Will return every row which has the name Spinning or Krachttraining.
Just use:
SELECT .FROM...WHERE AND sport.name LIKE '%".$sports."%'";
After question editing
After you changed the question, I suggest to take a look at this answer to better understand what you should to do: https://stackoverflow.com/a/3902567/1076753
Anyway I think that you have to learn a bit about the like command: http://www.mysqltutorial.org/mysql-like/
Change the sql to :
$sql = "SELECT gym.id FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND sport.name LIKE '%".$sports%."'";

Allowing users to search database for username/email and showing results

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!

Str_Replace with query results

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>";
}

MYSQL does not return result in PHP when asked for the first ranking only

I am trying to get hold of 1 record from a MySQL table using PHP. I have tried many different SELECT statements, while they all work in MYSQL they refuse to return any result in php.
The countriesRanking table is a simple two column table
country clicks
------ ------
0 222
66 34
175 1000
45 650
The mysql returns the ranking of the country column (1, 2, 3, etc..) and it returned all results EXCEPT the first ranked country. Eg when country=175, should return 1 but no result returned. Direct query via web browser return blank page, no error message. My PHP code
$result = mysql_query("SELECT FIND_IN_SET(clicks,
(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC)
FROM countriesRanking)) rank FROM countriesRanking
WHERE country = '$country'") or die(mysql_error());
$row = mysql_fetch_assoc($result) or die(mysql_error());
$theranking = $row['rank'];
echo $theranking;
EDIT
I tried the following but get the same blank page
var_dump($row['rank']);
EDIT 2
For a successful query print_r($result) returned something like Resource id #4. While print_r($row) returned Array ( [0] => 4 [rank] => 4 ). But when querying for the top ranking country. eg country=175, it returned a blank page.
Give this a try. It is based on your earlier question. MYSQL returns empty result in PHP
MYSQLI version:
<?PHP
function rank(){
/* connect to database */
$hostname = 'server';
$user = 'username';
$password = 'password';
$database = 'database';
$link = mysqli_connect($hostname,$user,$password,$database);
/* check connection */
if (!$link){
echo ('Unable to connect to the database');
}
else{
$query = "SELECT COUNT(*) rank FROM countryTable a JOIN countryTable b ON a.clicks <= b.clicks WHERE a.country = 175";
$result = mysqli_query($link,$query);
$arr_result = mysqli_fetch_array($result,MYSQLI_BOTH);
return $arr_result['rank'];
}
mysqli_close($link);
}
echo rank();
?>
MYSQL version:
<?PHP
function rank(){
/* connect to database */
$hostname = 'server';
$user = 'username';
$password = 'password';
$database = 'database';
$link = mysql_connect($hostname,$user,$password);
/* check connection */
if (!$link){
echo ('Unable to connect to the database');
}
else{
$query = "SELECT COUNT(*) rank FROM countryTable a JOIN countryTable b ON a.clicks <= b.clicks WHERE a.country = 66";
mysql_select_db($database);
$result = mysql_query($query);
$arr_result = mysql_fetch_array($result,MYSQL_BOTH);
return $arr_result['rank'];
}
mysql_close($link);
}
echo rank();
?>
Assuming you are not getting an error that means you are successfully connecting to your database. You are just not getting back any values.
Try:
$row = mysql_fetch_row($result);
I would usually think $row = mysql_fetch_assoc($result); would work but if neither of these work it must be something within your mysql_query.
You can debug this as below.
make sure your SQL is correct by running it on PHPMyAdmin and check the result.
make sure you don't have any fatal errors, if you get a blank page there is something wrong. Turn on PHP errors and see.
print_r($result) and see whether it's empty.
if you want first ranking only then add the LIMIT 1 to your query
If you want only one record from database than you have to use limit in query
$result = mysql_query("SELECT FIND_IN_SET(clicks,
(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC)
FROM countriesRanking)) rank FROM countriesRanking
WHERE country = '$country' LIMIT 1") or die(mysql_error());
and after that use while loop
while($row = mysql_fetch_assoc($result)) {
$theranking = $row['rank'];
}
echo $theranking;

Categories