Get data from a table with my foreign key? - php

Currently I want to get data from another table with my foreign key.
I have already setup my foreign key.
I have tables setup like this:
CREATE TABLE IF NOT EXISTS `album` (
`album_ID` int(11) NOT NULL AUTO_INCREMENT,
`album_navn` varchar(150) NOT NULL,
PRIMARY KEY (`album_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
--
--
INSERT INTO `album` (`album_ID`, `album_navn`) VALUES
(1, 'Nytår'),
(2, 'Berlin'),
(3, 'Færøerne'),
(5, 'TEST');
CREATE TABLE IF NOT EXISTS `billeder` (
`billeder_ID` int(11) NOT NULL AUTO_INCREMENT,
`billeder_navn` varchar(150) NOT NULL,
`billeder_fotograf` varchar(150) NOT NULL,
`billeder_sti` varchar(150) NOT NULL,
`fk_album_ID` int(11) NOT NULL,
PRIMARY KEY (`billeder_ID`),
KEY `fk_album_ID` (`fk_album_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=54 ;
--
--
INSERT INTO `billeder` (`billeder_ID`, `billeder_navn`, `billeder_fotograf`, `billeder_sti`, `fk_album_ID`) VALUES
(24, 'Vi tester4', 'Nytår', 'full_nytaar.jpg', 1),
(25, '', 'Nytår', 'full_nytaar2.jpg', 1),
(26, '', 'Nytår', 'full_nytaar4.jpg', 1),
Where I want to get ALBUM_NAVN via my fk_album_ID
so it will be possible to get it like this:
$row[album_navn]
I have tried to do it, but im lost.
Thanks in advance.
Regards, Kristian

Please try this query
SELECT * FROM billeder LEFT JOIN album ON billeder.fk_album_ID = album.album_ID

Try:
select * from billeder left join album where billeder.fk_album_ID=album.album_ID

This query will bring the desired result.
SELECT b . * , a.album_navn FROM `billeder` b, album a WHERE b.fk_album_ID = a.album_ID
Please try this php code as well. This is working and tested. You need to use join in query.
// CONNECT TO THE DATABASE
$DB_NAME = 'test';
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//query
$query = " SELECT b . * , a.album_navn FROM `billeder` b, album a
WHERE b.fk_album_ID = a.album_ID";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
// show data
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo ($row['album_navn']);
}
}
else {
echo 'No record found';
}
//close conn
mysqli_close($mysqli);

Related

i want to create status and comment system similar to facebook

i just want to build comment and status system similar to facebook. when i give a status its show and comment regarding this status its show. but when i give a new status it dose not show.
<?php
// show status.
mysql_connect("localhost","root","");
mysql_select_db("saif");
$sql="select id, st from status ";
$result=mysql_query($sql);
while($row= mysql_fetch_array($result))
{
echo $row['id']. " " .$row['st'];
echo "<br>";
//show comment;
mysql_connect("localhost","root","");
mysql_select_db("saif");
$sql="select com from comment ";
$result=mysql_query($sql);
while($row= mysql_fetch_array($result))
{
echo $row['com'];
echo "<hr>";
}
// end of show comment
//new comment area.
include('textarea.php');
echo "<hr>";
}
?>
Ok, this is my solution:
First I create two tables in my db and I populated them, then I create a connection to my db using MySQLi (MySQL is deprecated).
I SELECTED all the status, and for each status I selected the related comments. To do so, In the comments table I need something to make a relation between status and comments.
Just to understand to which status the comment is related.
First let's create and populate the tables:
SQL:
CREATE TABLE `status` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`st` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `status` (`id`, `st`)
VALUES
(1, 'This is the first status in your DB, let\'s say \"Hello World\"'),
(2, 'This is the second status');
CREATE TABLE `comment` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`id_status` int(11) DEFAULT NULL,
`com` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `comment` (`id`, `id_status`, `com`)
VALUES
(1, 1, 'This is just a comment to the first status'),
(2, 1, 'This is another comment to the first status'),
(3, 2, 'This is a comment to the second status'),
(4, 1, 'This is the third comment to the first status');
Ok, the php file:
<?php
$con = mysqli_connect("localhost","YourUsername","YourPassword","YourDB");
// Check connection
if (mysqli_connect_errno()) {
echo "Connection error: ".mysqli_connect_error();
exit();
}
$sql = "SELECT * FROM status";
$result = $con->query($sql);
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo $row['id']." ".$row['st']."<br>";
//show comment
echo "<ol>";
$id_status = $row['id'];
$query = "SELECT com FROM comment WHERE id_status = $id_status";
$comments = $con->query($query);
while($comment = $comments->fetch_array(MYSQLI_ASSOC))
{
echo "<li>".$comment['com']."</li>";
}
echo "</ol>";
// end of show comment
//new comment area.
include('textarea.php');
echo "<hr>";
}
?>
And this is the result (no text area in my output, cause I didn't have your textarea.php)
I hope this helps.

I want to display data according to product p_id

My 3 tables namely product, band, product Info
Product
CREATE TABLE IF NOT EXISTS `product` (
`p_id` int(11) NOT NULL AUTO_INCREMENT,
`product` varchar(50) NOT NULL,
PRIMARY KEY (`p_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `product` (`p_id`, `product`) VALUES
(1, 'Atta'),
(2, 'OIl');
Brand
CREATE TABLE IF NOT EXISTS `brand` (
`b_id` int(11) NOT NULL AUTO_INCREMENT,
`p_id` int(11) NOT NULL,
`brand` varchar(50) NOT NULL,
`image` varchar(255) NOT NULL,
PRIMARY KEY (`b_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
Insert
INSERT INTO `brand` (`b_id`, `p_id`, `brand`, `image`) VALUES
(1, 1, 'Ashirvad', 'FreeVector-Blue-Squares-Vector.jpg'),
(2, 1, 'Phillsberry', 'ILBAGNOALESSI_One_02.jpg'),
(3, 2, 'Sunflower', '001-bi-fold-corporate-brochure-template-vol-1-2.jpg');
Product Info
CREATE TABLE IF NOT EXISTS `product_info` (
`pi_id` int(11) NOT NULL AUTO_INCREMENT,
`pro` int(11) NOT NULL,
`b_id` int(11) NOT NULL,
`quantity` varchar(20) NOT NULL,
`measurement` varchar(20) NOT NULL,
`mrp` varchar(20) NOT NULL,
`our_price` varchar(20) NOT NULL,
PRIMARY KEY (`pi_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
Insert
INSERT INTO `product_info` (`pi_id`, `pro`, `b_id`, `quantity`, `measurement`, `mrp`, `our_price`) VALUES
(1, 1, 1, '1', 'kg', '50', '48'),
(2, 1, 2, '1', 'kg', '60', '59'),
(3, 2, 3, '1', 'ltr', '90', '86');
When i use the below query to display data according to the p_id, it displays data correctly
<?php
// Make a MySQL Connection
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not Connect to DB :'. mysql_error());
}
mysql_select_db("mr_bazaar",$con);
$result = mysql_query("select * FROM product");
echo '<ul class="list-1 p2">';
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo '<li>';
echo "<a href='page1.php?$row[p_id]'>";
echo '<b>';
echo $row['product'];
echo '</b>';
echo "</a>";
echo '</li>';
}
echo '</ul>';
mysql_close($con);
?>
and I want to display data according to the p_id in another page page1.php using the table product, brand, product_info(product from product table),(brand from brand table), (quantity, mrp from product_info table)
Send the product id to the next page as a URL parameter. So change,
echo "<a href='page1.php?$row[p_id]'>";
to
echo "<a href='page1.php?pid=$row[p_id]'>";
and accept the pid in page1.php using
$pid=$_GET['pid']; // getting the URL parameter
Now you can query to get the details corresponding to the pid.
mysql_query("SELECT p.product,b.brand,pi.quantity,pi.mrp FROM product as p INNER JOIN brand as b ON p.p_id=b.p_id
INNER JOIN product_info as pi ON pi.b_id=b.b_id WHERE p.p_id=$pid");
1- For sending the product id to page1.php, pass the variable correctly, change
echo "<a href='page1.php?$row[p_id]'>";
to
echo "<a href='page1.php?pid=$row[p_id]'>";
2- Get the variable on page1.php using:
$pid = $_GET['pid'];
3- Query the database for record of that product
$result = mysql_query("select * FROM product WHERE p_id='{$pid}'");
*Note:
1- I would recommend you not to use mysql_* function use mysqli or pdo library instead, and also escape the string while getting it from GET parameter.
2- You can use joins to fetch data from other tables corresponding to current product

Getting NULL in JSON

I'm following this website to create mySQL table and php in order to convert data to JSON
SQL:
CREATE TABLE IF NOT EXISTS `employee` (
`id_employee` int(3) unsigned NOT NULL AUTO_INCREMENT,
`emp_name` varchar(10) DEFAULT NULL,
`designation` varchar(9) DEFAULT NULL,
`date_joined` date DEFAULT NULL,
`salary` decimal(7,2) DEFAULT NULL,
`id_dept` int(2) DEFAULT NULL,
PRIMARY KEY (`id_employee`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;
INSERT INTO `employee` (`id_employee`, `emp_name`, `designation`, `date_joined`, `salary`, `id_dept`) VALUES
(1, 'SMITH', 'CLERK', '2010-12-17', 2500.00, 20),
(2, 'ALLEN', 'SALESMAN', '2005-02-20', 3500.00, 30),
(3, 'WARD', 'SALESMAN', '2009-02-22', 3550.00, 30),
(4, 'JONES', 'MANAGER', '2010-04-02', 3975.00, 20),
(5, 'MARTIN', 'SALESMAN', '2011-09-28', 3300.00, 30);
PHP:
<?php
//Create Database connection
$db = mysql_connect("localhost","root","root");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("test_json",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from employee", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id_employee'] = $row['id_employee'];
$row_array['emp_name'] = $row['emp_name'];
$row_array['designation'] = $row['designation'];
$row_array['date_joined'] = $row['date_joined'];
$row_array['salary'] = $row['salary'];
$row_array['id_dept'] = $row['id_dept'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
However, i get 2 results with null and no other errors:
[{"id_employee":null,"emp_name":null,"designation":null,"date_joined":null,"salary":null,"id_dept":null},{"id_employee":null,"emp_name":null,"designation":null,"date_joined":null,"salary":null,"id_dept":null}]
I just copied the code and try to run it, how come there is no return in the result??
Can someone points out what's wrong with my code??
Or it is my server problem??
PHP version:5.2
MySQL ver. :5.1
Thank you
Please have a look at mysql_set_charset(). As about JSON itself, last error can be fetched with json_last_error().
You should replace mysql_fetch_array to mysql_fetch_assoc so you can access the variable by column name.
Also, you should start using mysqli instead of mysql, to connect and interact wth mysql database from php.

Create 2nd tables and add data

I have this task from school, and I am confuse and lost on how I got to do this.
So basically I have to create 2 tables to the database but I have to created from php.
I have created the first table, but not the second one for some reason.
And then, I have to populate first and second tables with 10 and 20 sample records respectively, populate, does it mean like adding more fake users? if so is it like the code shown below?
*I got error on the populating second part as well
Thank you so much for the help.
<?php
$host = "host";
$user = "me";
$pswd = "password";
$dbnm = "db";
$conn = #mysqli_connect($host, $user, $pswd, $dbnm);
if (!$conn)
die ("<p>Couldn't connect to the server!<p>");
$selectData = #mysqli_select_db ($conn, $dbnm);
if(!$selectData)
{
die ("<p>Database Not Selected</p>");
}
//1st table
$sql = "CREATE TABLE IF NOT EXISTS `friends`
(
`friend_id` INT NOT NULL auto_increment,
`friend_email` VARCHAR(20) NOT NULL,
`password` VARCHAR(20) NOT NULL,
`profile_name` VARCHAR(30) NOT NULL,
`date_started` DATE NOT NULL,
`num_of_friends` INT unsigned,
PRIMARY KEY (`friend_id`)
)";
//2nd table
$sqlMyfriends = "CREATE TABLE `myfriends`
(
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL,
)";
$query_result1 = #mysqli_query($conn, $sql);
$query_result2 = #mysqli_query($conn, $sqlMyfriends);
//populating 1st table
$sqlSt3="INSERT INTO friends (friend_id, friend_email, password, profile_name, date_started, num_of_friends)
VALUES('NULL','email#email.com','123','abc','2012-10-25', 5)";
$queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2)";
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
mysqli_close($conn);
?>
The others have addressed one of your issues, so this is in relation to not being able to add values to your tables (populate). Your connection link is $conn -
$conn = #mysqli_connect($host, $user, $pswd, $dbnm);
ie.
$query_result1 = #mysqli_query($conn, $sql);
but when you are adding your values to the tables, you changed your connection link to $dbConnect
...
$queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
...
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
To insert multiple values into your table you could add a comma and additional parentheses ,() -
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2),(2,3),(3,1)";
$queryResult13=#mysqli_query($conn,$sqlSt13);
Or you could use mysqli_multi_query, and list each one-
//populating 2nd table
$sqlSt13 ="INSERT INTO myfriends VALUES (1,2);";
$sqlSt13 .="INSERT INTO myfriends VALUES (2,3);";
$sqlSt13 .="INSERT INTO myfriends VALUES (3,1);";
$queryResult13=#mysqli_query($conn,$sqlSt13);
see the manual for mysqli_multi_query - php.net/manual/en/mysqli.multi-query.php
You have an extra comma here that might cause an error:
friend_id2 INT NOT NULL,
should be:
$sqlMyfriends = "CREATE TABLE `myfriends` (
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL
)";
I wish I could be at school now :)
You have the following errors in code:
1) $queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
Is correct: $queryResult3 = #mysqli_query($dbConnect,$sqlSt3);
2) $sqlMyfriends = "CREATE TABLE myfriends
(
friend_id1 INT NOT NULL,
friend_id2 INT NOT NULL,
)";
Is correct: $sqlMyfriends = "CREATE TABLE myfriends
(
friend_id1 INT NOT NULL,
friend_id2 INT NOT NULL)";
3) $queryResult3 = #mysqli_query($conn,$sqlSt3);
Is correct: $queryResult3 = mysqli_query($conn,$sqlSt3);
Code correct is:
Couldn't connect to the server!");
$selectData = #mysqli_select_db ($conn, $dbnm);
if(!$selectData)
{
die ("Database Not Selected");
}
//1st table
$sql = "CREATE TABLE IF NOT EXISTS `friends`
(
`friend_id` INT NOT NULL auto_increment,
`friend_email` VARCHAR(20) NOT NULL,
`password` VARCHAR(20) NOT NULL,
`profile_name` VARCHAR(30) NOT NULL,
`date_started` DATE NOT NULL,
`num_of_friends` INT unsigned,
PRIMARY KEY (`friend_id`)
)";
//2nd table
$sqlMyfriends = "CREATE TABLE `myfriends`
(
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL
)";
$query_result1 = #mysqli_query($conn, $sql);
$query_result2 = #mysqli_query($conn, $sqlMyfriends);
//populating 1st table
$sqlSt3="INSERT INTO friends (friend_id, friend_email, password, profile_name, date_started, num_of_friends)
VALUES('NULL','email#email.com','123','abc','2012-10-25', 5)";
$queryResult3 = mysqli_query($conn,$sqlSt3);
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2)";
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
mysqli_close($conn);
?>
I hope to help !

Insert record failing! php mysqli

i have a mysql database...
CREATE TABLE `applications` (
`id` int(11) NOT NULL auto_increment,
`jobref` int(11) NOT NULL,
`userid` int(11) NOT NULL,
`q1` text NOT NULL,
`q2` text NOT NULL,
`q3` text NOT NULL,
`sub_q1` text,
`sub_q2` text,
`sub_q3` text,
`timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
`printed` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `jobref` (`jobref`),
KEY `applications_ibfk_2` (`userid`),
CONSTRAINT `applications_ibfk_1` FOREIGN KEY (`jobref`) REFERENCES `jobs` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `applications_ibfk_2` FOREIGN KEY (`userid`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='InnoDB free: 9216 kB; (`jobref`) REFER `iwcjobs/jobs`(`id`) '
and this php file, using mysqli for data operations.
<?php
require_once '../includes/constants.php';
if(isset($_POST['submit'])) {
$q1 = $_POST['question1'];
$q1a = $_POST['ifNoQuestion1'];
$q2 = $_POST['question2'];
$q2a = $_POST['ifNoQuestion2'];
$q3 = $_POST['question3'];
$q3a = $_POST['ifNoQuestion3'];
$JobRef = $_POST['jobref'];
$UserRef = $_POST['id'];
$mysql = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was a problem connecting to the database');
if($stmt = $mysql->prepare('INSERT INTO `applications` VALUES (NULL,?,?,?,?,?,?,?,?,NULL,NULL)')) {
$stmt->bind_param('iissssss',$JobRef,$UserRef,$q1,$q2,$q3,$q1a,$q2a,$q3a);
$stmt->execute();
$stmt->close();
header('location: ../myApps.php?apr=y');
//echo ("<h2>success</h2> - $q1 . $q2 . $q3 . $q1a . $q2a . $q3a . $JobRef . $UserRef");
} else {
echo 'error: ' . $mysql->error;
}
} else {
echo 'errorStage2: ' . $mysql->error;
}
?>
The script is grabbing the correct values from the previous form, but not inserting them into the database. Any ideas people?
Thx in advance,
Aaron.
the way your insert query is currently written, you are trying to set id to NULL, which is a NOT NULL field.
it'd be better to structure the insert would be like this:
INSERT INTO 'applications' (jobref,userid,etc..) VALUES (?,?etc..)
this way, you not try to change id, and just let auto_increment do it's thing.

Categories