Search for form element in database multiple times - php

I am trying to learn php and came across a task which i have need help with.
Background information - I have a postgresql database which has
multiple tables.
What I need - When I enter anything in the form on my HTML page, i
need to extract all information from all the tables that contain
information related to what I have entered.
Example - Suppose I enter food poisoning in the form. I need to access
all the tables and extract the different information related to food
poisoning.
My code: (the connection part is not being posted as it works fine)
<?php
$result = pg_prepare($dbh, "Query1", 'SELECT * FROM Project.bacteria WHERE disease = $1');
// if (pg_numrows($result) == 0) {
// $result = pg_prepare($dbh, "Query1", 'SELECT * FROM Project.virus WHERE disease = $1');
// }
//$sql = "SELECT * FROM Project.bacteria WHERE disease=";
//$result = pg_query($dbh, $sql);
$result = pg_execute($dbh, "Query1", array($disease));
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
//$rows = pg_fetch_all($result)
/*// iterate over result set
// print each row*/
while ($row = pg_fetch_array($result)) {
echo $row[0]." ".$row[1]. "<br />";
}
?>
For the above code, when I enter food poisoning it searches just one table i.e bacteria and returns the related information ( here as a test i have taken just information at row position 1 and row position 2.)
Since there are multiple tables, like a table drugs that stores information of drugs used to cure food poisoning, i would want to extract that information from the respective table.
Any help would be appreciated.

try this one
SELECT * FROM bacteria WHERE disease = ''
UNION ALL
SELECT * FROM drugs where desease = ''
but i think the best way is to normalize you tables. :)

Related

show same id one time but in column count how many times php

I am displaying data from database, but I want to display one time same id but in other column how many times its stored in MySQL database.
Thanks!
if (!isset($_REQUEST['completed_consu_id'])) {
$query = "SELECT * FROM completed_consumers";
} else {
$query = "SELECT * FROM completed_consumers WHERE consu_id=consu_id";
}
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$numberofrow=mysql_num_rows($result);
while ($row = #mysql_fetch_array($result)) {
$consu_id = $row['consu_id'];
$consu_first_name = $row['consu_first_name'];
$consu_last_name = $row['consu_last_name'];
$consu_phone = $row['consu_phone'];
$consu_email = $row['consu_email'];
$consu_address = $row['consu_address'];
$consu_city = $row['consu_city'];
$consu_state = $row['consu_state'];
$consu_zip = $row['consu_zip'];
$consu_IP = $row['consu_IP'];
$status = $row['status'];
$query2 ="SELECT consu_id, COUNT(*) FROM completed_consumers WHERE consu_id=$consu_id GROUP BY consu_id";
$result2 = mysql_query($query2) or die('Query failed: ' . mysql_error());
$numberofrow2=mysql_num_rows($result2);
$times= $numberofrow2;
echo $times;
This is code i have written, Its displaying all the consumers details and how many they have entered data or details, but I want to show one time consumer details/Name but how many time they submitted data in "times" column.
Like David consumer added 2 times, Monika added 1 time, Arshi added 3 times data/details, but when i retrieve data its showing 6 rows in table, i want to show in 3 row, 1 for David, 1 for Monika, 1 for Arshi but with how many times they added in "times" column when i retrieve it details.
Take a look at the GROUP BY clause.
SELECT id, COUNT(*) FROM completed_consumers WHERE consu_id=$consu_id GROUP BY consu_id

PHP MySQL: Fetching all associated rows from multiple tables using one query?

For a recipe app I've got one table storing general recipe info and an id. I've then got several other tables tables storing associated data like ingredients, instructions, notes and so on. At the moment I'm fetching and connecting all this data using multiple simple SQL statements.
However I now need to put the entire result (everything relating to one recipe, via its "recipe_id") into one single array so that I can manipulate it as one entity.
I first tried array_merge but then got on using JOINs but I'm not certain that they do what I like. Is that the route I need to take of are there other options?
Here is my current code:
$conn = connDB();
// Get basic recipe data
$sql = "SELECT recipe_id, date_created, name, description, author, cooktime, preptime, totaltime, yield, category_id, cuisine_id, image, image_url, url FROM recipes WHERE recipe_id=" . $recipe_id . " LIMIT 1";
$result = $conn->query($sql);
// Check that we get a result - ie a valid recipe_id
if ($result->num_rows > 0) {
$basicrow = $result->fetch_assoc();
// Get ingredients
$sql = "SELECT recipe_id, ingredient_id, ingredient, uom_id, ingredient_quant FROM ingredients WHERE recipe_id=" . $recipe_id . "";
$ingredientresult = $conn->query($sql);
$ingredientrow = $ingredientresult->fetch_assoc();
// Get Units Of Measurements
$sql = "SELECT uom_id, uom_long, uom_short FROM uom";
$uomresult = $conn->query($sql);
if ($uomresult->num_rows > 0) {
$uomArray = array();
while($uomrow = $uomresult->fetch_assoc()) {
$uomArray[$uomrow['uom_id']]["uom_id"] = $uomrow['uom_id'];
$uomArray[$uomrow['uom_id']]["uom_long"] = $uomrow['uom_long'];
$uomArray[$uomrow['uom_id']]["uom_short"] = $uomrow['uom_short'];
}
}
// Get instructions
$sql = "SELECT recipe_id, instruction_id, instruction FROM instructions WHERE recipe_id=" . $recipe_id . "";
$instructionresult = $conn->query($sql);
// Get notes
$sql = "SELECT recipe_id, date_created, note FROM notes WHERE recipe_id=" . $recipe_id . "";
$notesresult = $conn->query($sql);
} else {
echo "No such recipe"; // Not a valid recipe_id
}
$conn->close();
You could create associative arrays keyed off of recipe id, then you could loop through them and combine the information in the form you want. Using joins is the best way to get this data in one array. The only caveat I have with this is how long it takes the queries to run. I have personally used both approaches, it all depends on what I'm trying to do, and how long it takes the page in question to load.

How to grab an int from my MySQL server via PHP?

I am a novice when it comes to PHP but I don't understand if my syntax is wrong in this statement, or how would I grab an int from my MySQL server.
I know that my server credentials are working fine. How would I fix this statement to give me a returned integer of the number of reviews in the userinfo table?
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$amountofreviews = $numberofpreviousreviews + 1;
$query2 = mysql_query("ALTER TABLE userinfo ADD `amountofreviews` VARCHAR(10000)") or die(mysql_error()); //Make another column in database for the new review
You need to fetch your results after you run your query. There are several ways to do this but using mysql_fetch_assoc() will work for you.
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$row = mysql_fetch_assoc($numberofpreviousreviews);
$amountofreviews = $row['number_of_reviews'] + 1;
FYI, you shouldn't be using mysql_* functions anymore. They are deprecated and going away. You should use mysqli or PDO.
Assume you have a table userinfo which has the following structure and data :
Scenario #1 :
If you want to retrieve the all number_of_reviews, then do like this,
$query = "SELECT `number_of_reviews` FROM `userinfo`";
$result = mysqli_query($db,$query);
while ($row = mysqli_fetch_assoc($result)) {
echo "Number of reviews : " . $row['number_of_reviews'] . "<br/>";
}
It will give you,
Number of reviews : 20
Number of reviews : 40
Since, the result has many rows, it will display like above.
Scenario #2:
If you want to retrieve only the specific number_of_reviews for some user id (which is unique). I take id as 1 as a example here. Then do like,
$query2 = "SELECT `number_of_reviews` FROM `userinfo` WHERE `id` = 1";
$result2 = mysqli_query($db,$query2);
while ($row2 = mysqli_fetch_assoc($result2)) {
echo $row2['number_of_reviews'] . "<br/>";
}
This will print,
20.
Because, number_of_reviews is 20 for id 1.

need help creating a mysql query

Let's assume I a have a table called "users" which has the following relevant columns:
username
zipcode
Let's also assume I have a table called "shops" which has the following relevant columns:
shop_name
zipcode
Let's also assume I have a table called "preferred_shops" which has the following relevant columns:
shop_name
username
Let's also assume I have a table called "zipData" which has the following relevant columns:
zipcode
lat
lon
Currently I can run this code with success:
$lat="49.886436"; // Value should be obtained from the zipData table by doing a "SELECT FROM zipData WHERE zipcode=(users_zip_code)" or similar query
$lon="-97.14553"; // Value should be obtained from the zipData table by doing a "SELECT FROM zipData WHERE zipcode=(users_zip_code)" or similar query
$radius=5;
$query="SELECT zipcode FROM zipData
WHERE (POW((69.1*(lon-\"$lon\")*cos($lat/57.3)),\"2\")+
POW((69.1*(lat-\"$lat\")),\"2\"))<($radius*$radius)";
The query above will successfully display all the other zip codes that are within the given radius of the supplied lat/lon but I have no interest in knowing what other zip codes there are... I want to know what shops are within the radius.
Any help you can give would be greatly appreciated.
==== Edited because I realized it is actually a little more complex ====
This is what I need to do...
Retrieve the user's zipcode from "users" table
Find the user's lat/lon from the zipData table
Find all the shops within a given radius that is also in a "preferred_shops" table with the given user in the "username" column
Problems to consider: the zipcode in "zipData" has no white space but the zipcodes in "users" and "shops" have white space for cosmetic reasons... such as Canadian Postal codes which are in the "A1A 1A1" format
==== Edited to post solution ====
The system says I am not allowed to answer my own question. That sounds strange since with the help of others I already found the answer. As a work around I am editing the original post. Here is the solution...
Ok so I figured it out (with the help of the people that replied)... This is what I did.
IT LIKELY COULD BE A LOT SHORTER AND CLEANER SO PLEASE FEEL FREE TO MAKE IT BETTER IF YOU KNOW A BETTER WAY.
$query = "SELECT * FROM preferred_shops
WHERE `username`='{$_SESSION['account_name']}'
";
$result = mysql_query($query);
if (mysql_errno())
{
die( "ERROR ".mysql_errno($link) . ": " . mysql_error($link) );
}
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_array($result))
{
// Get user's preferences and postal code
$query2 = "SELECT * FROM seekers
WHERE `username`='{$_SESSION['account_name']}'
";
$result2 = mysql_query($query2);
if (mysql_errno())
{
die( "ERROR ".mysql_errno($link) . ": " . mysql_error($link) );
}
$num_rows2 = mysql_num_rows($result2);
$row2 = mysql_fetch_array($result2);
$radius=$row2['radius']; // Didn't mention that is column was in the table but that didn't matter... the value could have come from anywhere.
// Get user's lat/lon
// Remove white space from the postal code
$query3="SELECT * FROM zipData WHERE zipcode=replace('{$row2['postal']}',' ','')";
$result3 = mysql_query($query3);
if (mysql_errno())
{
die( "ERROR ".mysql_errno($link) . ": " . mysql_error($link) );
}
$num_rows3 = mysql_num_rows($result3);
$row3 = mysql_fetch_array($result3);
$lat=$row3["lat"];
$lon=$row3["lon"];
$query4="SELECT shop_name FROM zipData,shops
WHERE (POW((69.1*(lon-\"$lon\")*cos($lat/57.3)),\"2\")+POW((69.1*(lat-\"$lat\")),\"2\"))<($radius*$radius)
AND replace(shops.zipcode,' ','') = zipData.zipcode
AND shops.shop_name={$row['shop_name']}
";
$result4 = mysql_query($query4);
if (mysql_errno())
{
die( "ERROR ".mysql_errno($link) . ": " . mysql_error($link) );
}
$num_rows4 = mysql_num_rows($result4);
$num_jobs=$num_rows4;
$i=0;
while($row4 = mysql_fetch_array($result4))
{
$shopArray[$i]=$row4["shop_name"];
$i++;
}
var_dump($shopArray);
}
You need to join to the shops table
SELECT shop_name FROM zipData,shops
WHERE (POW((69.1*(lon-\"$lon\")*cos($lat/57.3)),\"2\")+
POW((69.1*(lat-\"$lat\")),\"2\"))<($radius*$radius) and
shops.zipcode = zipdata.zipcode
select shopname from shops where zipcode in ( <your other working query> )

mySQL database: printing specific row or rows from a db table

please assist. i have a database with a couple of tables and rows and i want the php to print specific rows as and when i want it to. at the moment it renders all the content of the spesific table on my webpage. in future, i would like it to display the contents of a specific table if a cirtain user is logged in so im going to do that when i understand if statements and get over this hurdle 1st. my code is as follows:
<?php
include 'connect-mysql.php';
echo "<br/>";
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}
?>
To fetch specific rows from a table you have to include a WHERE clause in your SQL statement.
For example:
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer WHERE customer_id = 2";
Match the WHERE xxxxx clause to any column in your table
You need to specifiy yor criteria as a where clause in the SQL
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer where RAMSCODE = %1";
$result = mysql_query($query,mysql_real_escape_string($yourcode)) or die (mysql_error());
Also you really need to Read the Manuals!
As far as i've get what you want is to display only that row from customers table, which customer is logged in. you can use some thing like this:
while($row = mysql_fetch_array($result))
{
if($row['CUSTOMER_NAME'] == " //Customer Logged In (customer name from session)"){
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}else{
//do nothing or continue with printing all
}
}
Hope this helps.

Categories