Using php, I am trying to link results from 3 tables that are connected by a same value. I would then like each dynamic set of related results to repeat as a while loop on the page. This is the result I would like:
artist->
series1->piece1, piece2
series2->piece3, piece4
Artists and series tables share a matched column named 'artist'. Series and piece table have a matched column name 'series'. I know these tables are linked through this same matched value in the database as on another page cascade delete is working.
Currently it only shows the series as an echo repeat loop but with no artist or piece related on either side. Like so: http://www.exhibitjewellery.com/artistindex.php
Whether a mysql_fetch_assoc is the right way, I am not sure. I am confused as to whether the tables are linking correctly at all or if the problem is how I have divided the body section for formatting. I have a feeling a multidimensional array may help or even nesting the tables but I haven't quite grasped how all the details combine throughout each section of the code. Please help!
PHP above the head:
<?php
mysql_select_db($database_connectmysql, $connectmysql);
$query_artistrecordset = "SELECT * FROM artists ORDER BY artist ASC";
$artistrecordset = mysql_query($query_artistrecordset, $connectmysql) or die(mysql_error());
$row_artistrecordset = mysql_fetch_assoc($artistrecordset);
$totalRows_artistrecordset = mysql_num_rows($artistrecordset);
mysql_select_db($database_connectmysql, $connectmysql);
$query_seriesrecordset = "SELECT * FROM series, artists WHERE series.artist=artists.artist ORDER BY exhibition ASC";
$seriesrecordset = mysql_query($query_seriesrecordset, $connectmysql) or die(mysql_error());
$resultseries = mysql_query($query_seriesrecordset);
$row_seriesrecordset = mysql_fetch_assoc($resultseries);
$totalRows_seriesrecordset = mysql_num_rows($seriesrecordset);
mysql_select_db($database_connectmysql, $connectmysql);
$query_piecerecordset = "SELECT * FROM pieces,series WHERE pieces.piece=series.series ORDER BY piece ASC";
$piecerecordset = mysql_query($query_piecerecordset, $connectmysql) or die(mysql_error());
$resultpiece = mysql_query($query_piecerecordset);
$row_piecerecordset = mysql_fetch_assoc($resultpiece);
$totalRows_piecerecordset = mysql_num_rows($piecerecordset);
?>
This is how I have tried to echo it in the body:
<div id="serieslist" align="right">
<?php echo $row_artistrecordset['artist']; ?><br />
<?php echo $row_artistrecordset['website']; ?><br />
<?php echo $row_artistrecordset['artist_statement']; ?><br />
<?php do { ?>
<?php echo $row_seriesrecordset['series']; ?><br />
<?php echo $row_seriesrecordset['exhibition']; ?><br />
<?php echo $row_seriesrecordset['series_statement']; ?><br />
<?php do { ?>
<?php echo $row_piecerecordset['piece']; ?><br />
<?php echo $row_piecerecordset['description']; ?><br />
<?php echo $row_piecerecordset['category']; ?><br />
<?php echo $row_piecerecordset['dimensions']; ?><br />
<?php echo $row_piecerecordset['price']; ?><br />
add to collection button<br />
<?php } while ($row_piecerecordset = mysql_fetch_assoc($resultpiece)); ?>
<?php } while ($row_seriesrecordset = mysql_fetch_assoc($resultseries)); ?>
</div>
</body>
</html>
<?php
mysql_free_result($artistrecordset);
mysql_free_result($seriesrecordset);
mysql_free_result($piecerecordset);
?>
Any help would be greatly appreciated as I have been working on this for days!
Working from your code, here's a version converted to mysqli, with some of the redundant lines removed. I haven't been able to test this, so a little debugging might be required.
<?php
$connectmysql = mysqli_connect("dbhost","dbuser","dbname","dbname") or die("Database error:".mysqli_connect_error);
$query_artistrecordset = "SELECT * FROM artists ORDER BY artist ASC";
$artistrecordset = mysqli_query($connectmysql, $query_artistrecordset) or die(mysqli_error);
$query_seriesrecordset = "SELECT * FROM series, artists WHERE series.artist=artists.artist ORDER BY exhibition ASC";
$seriesrecordset = mysqli_query($connectmysql, $query_seriesrecordset ) or die(mysqli_error);
$query_piecerecordset = "SELECT * FROM pieces,series WHERE pieces.piece=series.series ORDER BY piece ASC";
$piecerecordset = mysqli_query($connectmysql, $query_piecerecordset) or die(mysqli_error);
echo "<div id="serieslist" align="right">"
while ($row_artistrecordset = mysqli_fetch_assoc($artistrecordset)) {
echo $row_artistrecordset['artist'],"<br>";
echo $row_artistrecordset['website'],"<br>";
echo $row_artistrecordset['artist_statement'],"<br>";
while ($row_seriesrecordset = mysqli_fetch_assoc($seriesrecordset)) {
echo $row_seriesrecordset['series'],"<br>";
echo $row_seriesrecordset['exhibition'],"<br>";
echo $row_seriesrecordset['series_statement'],"<br>";
while ($row_piecerecordset = mysqli_fetch_assoc($piecerecordset)) {
echo $row_piecerecordset['piece'],"<br>";
echo $row_piecerecordset['description'],"<br>";
echo $row_piecerecordset['category'],"<br>";
echo $row_piecerecordset['dimensions'],"<br>";
echo $row_piecerecordset['price'],"<br>";
echo "add to collection button<br />";
} // end of pieces
} // end of series
} //end of artists
mysqli_free_result($artistrecordset);
mysqli_free_result($seriesrecordset);
mysqli_free_result($piecerecordset);
echo "</div>";
?>
</body>
</html>
Firs I recommend you use object oriented PHP. Keep this on a separate, secure page called db.php, or something:
//db.php
<?php
function db(){
return new mysqli('replaceWithHostName', 'relaceWithUserName', 'replaceWithPassWord', 'replaceWithDatebaseName');
}
?>
Now for your other page:
//other.php
<?php
include('db.php'); $db = db(); $nr = 'No Results Were Found'; $od = '<div>'; $cd = '</div>'; $br = '<br />'; $ar = $sr = $pr = '';
$artistrecordset = $db->query('SELECT * FROM artists ORDER BY artist ASC');
if(!$artistrecordset)die($db->error);
if($artistrecordset->num_rows > 0){
while($row_ar = $artistrecordset->fetch_assoc()){
$ar .= $od.$row_ar['artist'].$br.$row_ar['website'].$br.$row_ar['artist_statement'].$cd;
}
$artistrecordset->free();
}
else){
die($nr);
}
$seriesrecordset = $db->query('SELECT * FROM series, artists WHERE series.artist=artists.artist ORDER BY exhibition ASC');
if(!$seriesrecordset)die($db->error);
if($seriesrecordset->num_rows > 0){
while($row_sr = $seriesrecordset->fetch_assoc()){
$sr .= $od.$row_sr['series'].$br.$row_sr['exhibition'].$br.$row_sr['series_statement'].$cd;
}
$seriesrecordset->free();
}
else){
die($nr);
}
$piecerecordset = $db->query('SELECT * FROM pieces,series WHERE pieces.piece=series.series ORDER BY piece ASC');
if(!$piecerecordset)die($db->error);
if($piecerecordset->num_rows > 0){
while($row_pr = $piecerecordset->fetch_assoc()){
$pr .= $od.$row_pr['piece'].$br.$row_pr['description'].$br.$row_pr['category'].$br.$row_pr['dimensions'].$br.$row_pr['price'].$cd;
}
$piecerecordset->free();
}
else){
die($nr);
}
$db->close();
$head = '<html><head></head><body>'; //this could be your other info
echo "$head<div id='serieslist' align='right'>$ar$sr$pr$cd".
"<script type='text/javascript'>/*you should put your JavaScript here*/</script>".
'</body></html>';
?>
Really, you should use an external src for your JavaScript so it's cached. Sorry, if the format is hard to read. Use the scrollbars.
You missed to write while loop for $row_artistrecordset as you did also for others, see your code there are only two loops.
First try this query in something like phpMyAdmin to see if it gets the result you want.
SELECT *
FROM artists a
JOIN series s ON s.artist = a.artist
JOIN pieces p ON p.series = s.series
ORDER BY a.artist;
Then process the single result like this.
mysql_select_db($database_connectmysql, $connectmysql);
$q = "SELECT * FROM artists a
JOIN series s ON s.artist = a.artist
JOIN pieces p ON p.series = s.series
ORDER BY a.artist";
$result = mysql_query($q, $connectmysql) or die(mysql_error());
foreach ( $row = mysql_fetch_assoc($result) ) {
echo $row['artist'] . '<br />';
echo $row['website'] . '<br />';
echo $row['artist_statement'] . '<br />';
echo $row['series'] . '<br />';
echo $row['exhibition'] . '<br />';
echo $row['series_statement'] . '<br />';
echo $row['piece'] . '<br />';
echo $row['description'] . '<br />';
echo $row['category'] . '<br />';
echo $row['dimensions'] . '<br />';
echo $row['price'] . '<br />';
echo ' add to collection button<br />';
}
Ok you should also use mysqli or PDO as the mysql extension is now deprecated, but without changing everything and its not a like for like just add a i conversion, you could try this as an interim solution.
Related
I want to use a variable that comes from a table i MySQL and pass it to Another SQL-Query with PHP. Can´t get it to work and I can´t find out why.
Here is the code:
<html>
<head><title></title></head>
<body>
<div>
<?php
if (isset($_GET['read_blog_posts_scrolling']))
{
$result = mysql_query("SELECT blogpost.Blogpost_title, blog.Blogwriters_name, blogpost.Date
FROM blog
INNER JOIN blogpost ON blog.BlogID=blogpost.BlogID
WHERE blog.BlogID='$blogs_profile_id' // Here it is, it says undefined variable
ORDER BY blogpost.Date DESC")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<p>';
echo "Titel: " . "<strong>" . $row['Blogpost_title'] . "</strong>" . " - Bloggare " . $row['Blogwriters_name'] . " " . $row['Date'] . '<br />';
echo '<hr />';
echo '</p>';
}
}
?>
<?php
$result = mysql_query("SELECT BlogID, Blogwriters_name FROM blog")
or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$blogs_profile_id = $row['BlogID']; // I want to pass this value to above and use it in the query
echo '<p>';
echo $row['Blogwriters_name'] . '<br />';
//When clicking in this link I want the query to execute and values in BlogID to be passed
echo 'Choose blogwriter';
echo '</p>';
?>
</div>
</body>
</html>
it says the variable is undefined. How can I define it and pass the value when the a href-link is clicked?
Error is clear. Undefined variable:
You didn't defined this variable anywhere
before select statement
$blogs_profile_id
I think you need to add this variable in query string and get from $_GET.
UPDATE 1:
You have following issues in your code.
Missing blog_profile_id in your query string.
Undefined variable means you are using a variable but didn't defined.
Using mysql_* extension its deprecated
Solution:
Replace this:
echo 'Choose blogwriter';
With:
echo 'Choose blogwriter';
And than use that:
if (intval($_GET['blog_id']) > 0)
{
$blogs_profile_id = intval( $_GET['blog_id']);
$result = mysql_query("SELECT blogpost.Blogpost_title, blog.Blogwriters_name, blogpost.Date FROM blog INNER JOIN blogpost ON blog.BlogID=blogpost.BlogID WHERE blog.BlogID=".$blogs_profile_id." ORDER BY blogpost.Date DESC")
or die(mysql_error());
.....
Change the order of your queries. The second query code has to be coming first in order as below
<html>
<head><title></title></head>
<body>
<div>
<?php
$result = mysql_query("SELECT BlogID, Blogwriters_name FROM blog")
or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$blogs_profile_id = $row['BlogID']; // I want to pass this value to above and use it in the query
echo '<p>';
echo $row['Blogwriters_name'] . '<br />';
//When clicking in this link I want the query to execute and values in BlogID to be passed
echo 'Choose blogwriter';
echo '</p>';
?>
<?php
if (isset($_GET['read_blog_posts_scrolling']))
{
$result = mysql_query("SELECT blogpost.Blogpost_title, blog.Blogwriters_name, blogpost.Date
FROM blog
INNER JOIN blogpost ON blog.BlogID=blogpost.BlogID
WHERE blog.BlogID='"+$blogs_profile_id+"' // Here it is, it says undefined variable
ORDER BY blogpost.Date DESC")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<p>';
echo "Titel: " . "<strong>" . $row['Blogpost_title'] . "</strong>" . " - Bloggare " . $row['Blogwriters_name'] . " " . $row['Date'] . '<br />';
echo '<hr />';
echo '</p>';
}
}
?>
</div>
</body>
</html>
I've discoverd a bug into my script. I will try to explain it.
I've made 2 pages into category.php
This one here below shows all content related to a category:
/category.php?nameID=Test
When I go to the first content related to this category for example:
/category.php?nameID=Test&id=2 I receive information from MYSQL about post ID 2, also all posts related to that category named 'test' below. Which I clearly don't want to get. only the Post ID
<?php
// BEGIN OF SHOWING CONTENT PAGE
if (isset($_GET['id'])){
$naamID = mysql_real_escape_string($_GET['nameID']);
$id = mysql_real_escape_string($_GET['id']);
$idnext = $id + 1;
$gn = (" SELECT * FROM category WHERE name='".$naamID."'") or die(mysql_error());
$go = (" SELECT * FROM post WHERE id='".$id."'") or die(mysql_error());
$gnn = mysql_query($gn) or die(mysql_error());
$goo = mysql_query($go) or die(mysql_error());
$gnnn = mysql_fetch_array($gnn);
$gooo = mysql_fetch_array($goo);
?>
<?php
echo '<p>';
if(empty($gooo['youtube'])){
} else {
?> <h1> <?php echo htmlspecialchars($gooo["title"]); ?> </h1><br />
<?php
$fullurl1 = $gooo['youtube'];
$videoid1=substr($fullurl1,-11);
?>
<?php
echo '<p><i>Edit this post</i><br />';
echo '<iframe width="560" height="315" src="//www.youtube.com/embed/'.$videoid1.'" frameborder="0" allowfullscreen></iframe><br />';
echo '</p>';
}
if(empty($gooo['pic'])){
} else {
?> <h1> <?php echo htmlspecialchars($gooo["title"]); ?> </h1><br />
<?php
echo '<p><i>Edit this post</i><br />';
echo '<img src="'.$gooo["pic"].'" style="max-height: auto; max-width: 600px;"/><br></p>';
}
echo '</p>';
}
?>
I dont know what you exactly want please be specific
But your code should be like this ->
$gnn = mysql_query("SELECT * FROM category WHERE name='$naamID'") or die(mysql_error());
$goo = mysql_query("SELECT * FROM post WHERE id= $id ") or die(mysql_error());
$gnnn = mysql_fetch_array($gnn);
$gooo = mysql_fetch_array($goo);
The above code will fetch only one row from each table. Also you had put $id in single quotes that makes it a string
Comment below if you need more help
I have to print customer name once and all the products for each customer.My code is below.
<div id="Allproducts">
<?php
$AllprodsRes = $conn -> query("select * from sepproducts");
if($AllprodsRes ->num_rows > 0){
$result = $AllprodsRes -> fetch_array();
?>
<label for="name"><?php echo $result['name'] . " " . $result['surname']; ?></label>
<?php } ?>
<?php do{ ?>
<p><?php echo $result['product_name'] . " " //$result['count']; ?></p>
<?php }while($result = $AllprodsRes -> fetch_array()); ?>
</div>
view sepproducts
CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`#`localhost`
SQL SECURITY DEFINER
VIEW `sepproducts` AS
select
`customers`.`name` AS `name`,
`customers`.`surname` AS `surname`,
`custproducts`.`product_name` AS `product_name`,
count(0) AS `count`
from
(`custproducts`
join `customers` ON ((`custproducts`.`custid` = `customers`.`custid`)))
group by `custproducts`.`product_name`
Any help is welcome and appreciated.
Thanks in advance.
What you can use is something like the following (assuming you use MySQLi):
<?php
$con = new mysqli('localhost', 'username', 'password', 'db');
$query = $con->query('SELECT * FROM...');
$currentCustomer = null;
while ($result = $query->fetch_array()) {
$name = $result['name'] . ' ' . $result['surname'];
// Check to see if we're working with a new customer.
if ($currentCustomer != $name) {
echo $name . '<br />';
$currentCustomer = $name;
}
echo $result['product_name'] . '<br />';
echo $result['product_type'] . '<br />';
// ETC.
}
?>
Or if you only have one customer to worry about, use the following:
<?php
$con = new mysqli('localhost', 'username', 'password', 'db');
$query = $con->query('SELECT * FROM...');
if ($query->num_rows > 0) {
$result = $query->fetch_array();
echo $result['name'] . ' ' . $result['surname'] . '<br />';
do {
echo $result['product_name'] . '<br />';
echo $result['product_type'] . '<br />';
// ETC.
} while ($result = $query->fetch_array());
}
?>
In effect, it checks if records have been found and if so, writes one result to our array $result. We then output the customer's name OUTSIDE of the loop (so this only occurs once), then use a do...while() loop to continue through the rest of the result array.
I hope this helps!
Depending on the databse you use you could join multiple rows into a single column. Ultimately this is a display problem. I say keep doing what you are doing and in your view keep track of the current name in the loop and compare to the next name - if the name is the same ignore it, when the name differs set current_name to this new name and continue. This way each name only shows once.
The following code retrieves and displays the correct data from the database however it gets all the data. I need a way to assign each value it retrieves from the database to a PHP variable. For example, if it gets "Joe", "Henry", and "Robert" from the database, I'd like one variable for each of those and right now it returns and array with all the values.
<?php
dbCon();
$query1 = mysql_query("SELECT * FROM hosts WHERE name!=''");
while($row1 = mysql_fetch_assoc($query1)) {
$res = $row1['name'] . '<br />';
echo $res;
}
?>
<?php
function echoName($id) {
dbCon();
$query1 = mysql_query("SELECT * FROM hosts WHERE id='$id'");
while($row1 = mysql_fetch_assoc($query1)) {
$res = $row1['name'] . '<br />';
echo $res;
}
}
?>
<div id="joe_div">
<?
echoName("1");
?>
</div>
.....
<div id="henry_div">
<?
echoName("2");
?>
</div>
Declare variable variables as such:
while($row1 = mysql_fetch_assoc($query1)) {
$$row1['name'] = $row1['name']
}
echo $Joe; //returns Joe
Though I don't know why you would ever need that
if it gets "Joe", "Henry", and "Robert" from the database, I'd like one variable for each of those
So try this:
<?php
dbCon();
$query1 = mysql_query("SELECT * FROM hosts WHERE name!=''");
while($row1 = mysql_fetch_assoc($query1)) {
$$row1['name'] = $row1['name'];
}
echo $Joe;
echo $Henry;
echo $Robert;
?>
P.S: I don't know why you want to do this, but i am sure you have a better approach to solve your problem.
I'm starting with this small PHP and mysql script. How would i make it show the tasks by the taskupdated column?
$query = "SELECT * FROM tasks2 where owner=72";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo $row['ownername'];
echo ' - ';
echo $row['tasktitle'];
echo '<br/>';
echo $row['taskdetails'];
echo '<hr/>';
}
<?php
$query = "SELECT * FROM tasks2 WHERE owner=72 ORDER BY taskupdated";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo $row['ownername'];
echo ' - ';
echo $row['tasktitle'];
echo '<br />';
echo $row['taskdetails'];
echo '<hr />';
}
?>
If you want to sort them the other way, use ORDER BY taskupdated DESC instead.
SELECT * FROM tasks2 where owner=72 ORDER BY taskupdated