Recipe Finder with PHP and MySQL based on Ingredients - php

I am developing a cooking recipe-website and i want to create a recipe finder based on the used incredients.
My current finder only works with 3 ingredients right.
The Finder should return the right recipe(s) based on the used incredients (should work with 1-n*)
My Tables:
CREATE TABLE IF NOT EXISTS `INGREDIENTS` (
`ingredients_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`ingredients_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;
CREATE TABLE IF NOT EXISTS `INGREDIENTS_POS` (
`ingredients_pos_id` int(11) NOT NULL AUTO_INCREMENT,
`ingredients_id` int(11) NOT NULL,
`ingredients_unit` varchar(20) NOT NULL,
PRIMARY KEY (`ingredients_pos_id`),
KEY `ingredients_detail_fk` (`ingredients_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;
CREATE TABLE IF NOT EXISTS `RECIPES` (
`recipes_id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(50) COLLATE utf8_bin NOT NULL,
`text` varchar(2000) COLLATE utf8_bin NOT NULL,
`count_persons` int(11) NOT NULL,
`duration` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`date` datetime NOT NULL,
`accepted` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`recipes_id`),
KEY `recipes_user_fk` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=88 ;
CREATE TABLE IF NOT EXISTS `RECIPES_POS` (
`recipes_pos_id` int(11) NOT NULL AUTO_INCREMENT,
`recipes_id` int(11) NOT NULL,
`ingredients_id` int(11) NOT NULL,
`ingredients_value` int(11) NOT NULL,
PRIMARY KEY (`recipes_pos_id`),
KEY `recipe_pos_rec_id` (`recipes_id`),
KEY `recipes_pos_ingredient_fk` (`ingredients_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=58 ;
My buggy Solution (doesn't support count from 1-n):
<?php
include 'db_connect.php';
$q = urldecode(mysql_real_escape_string($_GET['q']));
$parameter = explode ('$',$q);
$var = 0;
//print_r($parameter);
foreach($parameter as $ing)
{
//echo $ing;
$sql = "SELECT ingredients_id FROM INGREDIENTS WHERE name='".$ing."'";
$result = mysql_query($sql,$db) or exit('{"Data":null,"Message":null,"Code":500}');
$row = mysql_fetch_array($result);
$arr_id[$var] = $row['ingredients_id'];
$var++;
}
//print_r($arr_id);
$sql = "SELECT r.recipes_id FROM RECIPES r, RECIPES_POS rp WHERE r.recipes_id = rp.recipes_id ";
foreach($arr_id as $id)
{
$sql .= "AND rp.ingredients_id =".$id . " ";
}
//echo $sql;
$result = mysql_query($sql,$db) or exit('{"Data":null,"Message":null,"Code":500}');
mysql_close($db);
$rec;
while($row = mysql_fetch_array($result))
{
//echo "test";
$_GET['id'] = $row['recipes_id'];
$rec= include('get_recipe_byID.php');
}
//print_r(mysql_fetch_array($result));
if (count($arr_id) == 0)
{
echo '{"Data":null,"Message":null,"Code":404}';
die();
}
?>
I need a better solution for that chase.
Maybe SQL itself will help me to find the right recipes
thx

That query helped me a lot:
select r.recipes_id
from RECIPES r
inner join RECIPES_POS rp on r.recipes_id = rp.recipes_id
where rp.ingredients_id in (4, 6)
group by r.recipes_id
having count(distinct rp.ingredients_id) = 2

Related

PHP If else and some logics

I just having some problem of if/else or somewhat logical things in here, I have a fullcalendar that shows all the date that being reserve, I limit the reserve by 5 per date, but when I having a 2 or more reserved on the date and having reserve by other date, It gives me the same result as 4.
global $db;
$data = array();
$query = "SELECT * FROM reserve_master
INNER JOIN reserve_details
on reserve_master.reserve_id = reserve_details.reserve_id
INNER JOIN reserve_indicator
on reserve_master.reserve_id = reserve_indicator.reserve_id
WHERE reserve_indicator.touserid = '$id'
AND reserve_master.type = 'Repair' ";
$res = mysqli_query($db,$query);
$count = mysqli_num_rows($res);
$count = 5 - $count;//count the available slot
$date_changed = "";
$reserve_id = 0;
foreach ($res as $row)
{
date_default_timezone_set('Asia/Manila');
$current_timestamp = strtotime($row["dateend"] . '+1 day');
$time = date("Y/m/d",$current_timestamp);
if($row["datestart"] == $date_changed)
{
//This is for avoiding repeating graph on fullcalendar
}
else
{
if(empty($count))
{
$count = '0';
}
else
{
$count;
}
$data[] = array(
'id' => $row["reserve_id"],
'title' => $count,
'start' => $row["datestart"],
'end' => $time,
'color' =>getColor($row["status"])
);
$date_changed = $row["datestart"];
$reserve_id = $row["reserve_id"];
}
}
echo json_encode($data);
This is image of the error with captions
Database
CREATE TABLE `reserve_master` (
`reserve_id` int(11) NOT NULL AUTO_INCREMENT,
`datestart` date NOT NULL,
`dateend` date NOT NULL,
`type` varchar(255) NOT NULL,
PRIMARY KEY (`reserve_id`)
) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=latin
CREATE TABLE `reserve_indicator` (
`indicator_id` int(11) NOT NULL AUTO_INCREMENT,
`reserve_id` int(11) NOT NULL,
`touserid` int(11) NOT NULL,
`byuserid` int(11) NOT NULL,
PRIMARY KEY (`indicator_id`),
KEY `reserve_id` (`reserve_id`) USING BTREE,
CONSTRAINT `reserve_indicator_ibfk_1` FOREIGN KEY (`reserve_id`) REFERENCES `reserve_master` (`reserve_id`)
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=latin1
CREATE TABLE `reserve_details` (
`details_id` int(11) NOT NULL AUTO_INCREMENT,
`reserve_id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
`status` varchar(255) NOT NULL,
`location` varchar(255) NOT NULL,
PRIMARY KEY (`details_id`),
KEY `reserve_id` (`reserve_id`) USING BTREE,
CONSTRAINT `reserve_details_ibfk_1` FOREIGN KEY (`reserve_id`) REFERENCES `reserve_master` (`reserve_id`)
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=latin1
All i had tried is to get the right available on the 2nd of febuary 2018 and not the others.
The code is mess, I'm very sorry;
Problem is solved already;
I use eventLimit on fullcalendar and set it to 1
Count = 5 not subtracted by the num_rows
and few set on if-statement
Few answer I used rows and res as it is easy to indicate for results and rows, and i used it same as other queries.
Thank you.

Error in query: Cannot delete or update a parent row: a foreign key constraint fails

I am trying to delete the contents from 3 tables which are associated with a certain User ID and I get the following error:
Error in query: Cannot delete or update a parent row: a foreign key constraint fails (`MyName_4.2c`.`tbl_reservation`, CONSTRAINT `tbl_reservation_ibfk_2` FOREIGN KEY (`propertyId`) REFERENCES `tbl_property` (`propertyId`))
Code:
<?php
session_start();
$userId = $_GET['userId'];
require_once('databaseConn.php');
$query = "DELETE FROM tbl_reservation WHERE userId = '$userId'";
$result = mysqli_query($connection, $query)
or die("Error in query: ". mysqli_error($connection));
$query2 = "DELETE FROM tbl_property WHERE userId = '$userId'";
$result2 = mysqli_query($connection, $query2)
or die("Error in query: ". mysqli_error($connection));
$query3 = "DELETE FROM tbl_users WHERE userId = '$userId'";
$result3 = mysqli_query($connection, $query3)
or die("Error in query: ". mysqli_error($connection));
header('Location: index.php');
?>
My Tables:
CREATE TABLE `tbl_property` (
`propertyId` int(11) NOT NULL,
`userId` int(11) NOT NULL,
`title` varchar(50) NOT NULL,
`capacity` int(11) NOT NULL,
`pricePerNight` double NOT NULL,
`locationId` int(11) NOT NULL,
`image` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `tbl_reservation` (
`reservationId` int(11) NOT NULL,
`propertyId` int(11) NOT NULL,
`date_from` date NOT NULL,
`date_to` date NOT NULL,
`amountPaid` double NOT NULL,
`userId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `tbl_users` (
`userId` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`surname` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `tbl_location` (
`locationId` int(11) NOT NULL,
`location` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Fetch all data in array

I am trying to add the direction, left and right member to direct but the problem now here is that I am only able to fetch one data (left_mem) instead of both left_mem and right_mem.
$query = $MySQLi_CON->query("select * from users where enroller_id='".$enroller_id_n."' ");
$direct = array();
if($query){
while ($row = $query->fetch_array()) {
$enroller_id3 = $row['enroller_id'];
$direct[] = $row['direction'];
}
}
if ($direct == "left_mem")
{
echo "success";
}
else {
echo "fail";
}
This is my database
CREATE TABLE `users` (
`user_id` int(11) NOT NULL,
`user_name` varchar(25) NOT NULL,
`user_email` varchar(255) NOT NULL,
`user_pass` varchar(255) NOT NULL,
`enroller_id` varchar(25) NOT NULL,
`enrolled_id` varchar(25) NOT NULL,
`direction` varchar(25) NOT NULL DEFAULT 'avail'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `users` (`user_id`, `user_name`, `user_email`, `user_pass`, `enroller_id`, `enrolled_id`, `direction`);
ALTER TABLE `users`
ADD UNIQUE KEY `user_id` (`user_id`);
ALTER TABLE `users`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
Use in_array to see if both values exist:
if (in_array('left_mem',$direct) && in_array('right_mem',$direct) )

mysqli multi query not executing the queries

I am trying to execute 3 queries to create tables within a database but it will not execute the query giving me a syntax error. Can anyone look at this code and tell me what I typed wrong to make this work? I have tried everything and I can not get the queries to execute!
$dh = mysqli_connect($_POST['hostname'], $_POST['username'], $_POST['password'], $_POST['database']);
if(! $dh )
{
die('Could not connect: ' . mysql_error());
}
echo "Connected successfully...<br /><br />";
$query = "CREATE TABLE IF NOT EXISTS `content` (
`content_id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`section_id` INT(11) NOT NULL,
`header` VARCHAR(255) NOT NULL,
`sub_header` VARCHAR(255) NOT NULL,
`date_range` VARCHAR(64) NOT NULL,
`content_body` TEXT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1";
$query .= "CREATE TABLE IF NOT EXISTS `sections` (
`section_id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`title` VARCHAR(255) NOT NULL,
`position` INT(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1";
$query .= "CREATE TABLE IF NOT EXISTS `sections` (
`user_id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`username` VARCHAR(32) NOT NULL,
`password` VARCHAR(32) NOT NULL,
`first_name` VARCHAR(32) NOT NULL,
`last_name` VARCHAR(32) NOT NULL,
`email` VARCHAR(1024) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1";
$retval = mysqli_multi_query($dh, $query);
You don't have semi colons between the queries and you are joining them all together and running at once.
If you are running multiple queries like that you need semicolons at the end of each query
$query = "CREATE TABLE IF NOT EXISTS `content` (
`content_id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`section_id` INT(11) NOT NULL,
`header` VARCHAR(255) NOT NULL,
`sub_header` VARCHAR(255) NOT NULL,
`date_range` VARCHAR(64) NOT NULL,
`content_body` TEXT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
$query .= "CREATE TABLE IF NOT EXISTS `sections` (
`section_id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`title` VARCHAR(255) NOT NULL,
`position` INT(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
$query .= "CREATE TABLE IF NOT EXISTS `sections` (
`user_id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`username` VARCHAR(32) NOT NULL,
`password` VARCHAR(32) NOT NULL,
`first_name` VARCHAR(32) NOT NULL,
`last_name` VARCHAR(32) NOT NULL,
`email` VARCHAR(1024) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
You are missing semicolons between queries.
So you are trying to execute something like this: <...> ENGINE=InnoDB DEFAULT CHARSET=latin1CREATE TABLE <...>

Select two columns from two tables and order by their values DESC

With this code I'm getting news from the database and order it by column "views":
<?php
$getnewsinfo = mysql_query("SELECT * FROM news ORDER BY views DESC LIMIT 5");
while($newsinforow = mysql_fetch_array($getnewsinfo))
{
$newsid = $newsinforow['id'];
$title = $newsinforow['title'];
$author = $newsinforow['author'];
$date = date('d.m.Y', $newsinforow['date']);
$picture = $newsinforow['picture'];
$picture_desc = $newsinforow['picture_desc'];
$category = $newsinforow['category'];
$text = $newsinforow['text'];
?>
Now I want to order the news by views and by the number of comments, but I have no idea how.
Here is my database structure :
CREATE TABLE IF NOT EXISTS `news` (
`id` int(11) NOT NULL auto_increment,
`views` int(11) NOT NULL default '0',
`title` varchar(255) NOT NULL,
`author` varchar(255) NOT NULL,
`date` varchar(255) NOT NULL,
`picture` varchar(255) NOT NULL,
`picture_desc` varchar(255) NOT NULL,
`category` varchar(255) NOT NULL,
`text` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
CREATE TABLE IF NOT EXISTS `news_comments` (
`id` int(11) NOT NULL auto_increment,
`news_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`website` varchar(255) NOT NULL,
`text` text NOT NULL,
`date` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=16 ;
I also want to ask you... do you have any comments on the code and database structure ?
Try this sql
SELECT n.*,count(nc.id) as cnt FROM news as n, news_comments as nc where n.id = nc.news_id group by nc.news_id ORDER BY views DESC,cnt DESC LIMIT 5

Categories