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

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.

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

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.

Search for form element in database multiple times

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. :)

Rewrite query depending on GET parameters

I'm working on a search engine on my website. Users can add on criteria which is submitted with a GET in the url.
When users select for example 1 criteria, it looks like this:
localhost/search.php?course=1&price=&name=
They have 3 criteria they can select, so as you see he only selected COURSE.
Now I have to select from the database according to the criteria so my code looks like this:
if ($_GET['price'] > 0 && $_GET['name'])
{
$search_price = $_GET['price'];
$search_name = $_GET['name'];
$result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id' AND price < $search_price AND name LIKE '%$search_name%'");
}
elseif ($_GET['price'] > 0)
{
$search_price = $_GET['price'];
$result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id' AND price < $search_price");
}
elseif ($_GET['name'])
{
$search_name = $_GET['name'];
$result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id' AND name LIKE '%$search_name%'");
}
else
{
$result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id'");
}
while ($row2 = mysql_fetch_assoc($result2))
{
.....
But this can not be the correct way, because if eventually users can select 10 criteria this is going to be a very long code
How do I fix this?
What I would do is dynamically create the sql query,and then execute it at the end. So something like this
$query_string = "SELECT blahblah, blahblah, blah blah from blahx where 1=1 ";
$where = "";
if(isset($_GET['somecriteria']))
{
$where .= " AND blahblah = $_GET['somecriteia'] ";
}
if(isset($_GET['someOTHERcriteria']))
{
$where .= " AND blahblah=$_GET['someOTHERcritera'] ";
}
mysql_query($query_string . $where);
etc..
Take note this is just to show you how to achieve your objective. This is obviously prone to SQL Injection attacks and you'd have to clean the stuff up.
Use $_post to send larger amounts of information to the php script. When using get you should create the url to include get calls only if they are populated. As such if no price is selected the url should not include "price=". This will cause problems with your receiving script.
Your database script can be done with one call including only the selected criteria.
Myqsl has been depreciated, you need to look into Myqsli or PDO

Simple way to read single record from MySQL

What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)

Categories