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.
Related
Recently I've bought webhosting at names.co.uk and I'm trying to set up something simple which will display the name from a table named Team if the id = 1.
This is my code
<?php
$q = "SELECT * FROM `Team` WHERE id =1";
$result = mysql_query($q);
echo '<br />Query is send';
echo '<br />Result is true';
$row = mysql_fetch_array($result);
echo '<br />tryed fetching row';
if ($row === FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
echo( mysql_error());
}
echo $name;
?>
This is the output:
Query is send Result is true tryed fetching rowNo such file or
directory
UPDATE:
I have changed to msqli:
$q = "SELECT * FROM `Team` WHERE id =1";
$result = mysqli_query($q);
echo '<br />Query is send';
echo '<br />Result is true';
$row = mysqli_fetch_array($result);
echo '<br />tryed fetching row';
if ($row !== FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
echo( mysqli_error());
}
echo $name;
and now I'm getting this output:
Query is send Result is true tryed fetching row $row is not false.
$name now is ""
You need to fist establish a connection. For example: $connection = mysqli_connect($servername, $username, $password);.
See this link on how to use MySQLi: https://www.w3schools.com/PHP/php_mysql_connect.asp (but note that w3schools is a bad resource, with outdated information and bad practices - I'm only linking to it because this tutorial is basic and clear).
Be sure to check later, if you still haven't, on how to properly sanitize your queries. See this, for example: How can I prevent SQL injection in PHP?
Use function:
$result = mysqli_query($q);
mysql_query() have been deprecated in PHP7 onwards.
I was experimenting if I could use a mySQL database to store CSS settings. I set up a simple database "colors" with one table "color" that had simple structure tag and color columns. In that, one row is h1 => red.
<?php
//function to dynamically change CSS
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
?>
When I tried to convert to a function, the code does not work at all.
<?php
//function to dynamically change CSS
function getCSS($tag)
{
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
}
getCSS('h1');
?>
Help please?
My guess is that in
$query = mysqli_query($link, $q);
$link goes out of scope and is empty. You should pass it to the function as well.
For the record: using $tag without escaping could be an sql injection attack possibility.
in function, there is no $link, you shoud define it as a global variable.
At the start of your function add a reference to your global DB link:
function getCSS($tag) {
global $link;
...
This should work:
<?php
$link = mysqli_connect('server_host', 'user', 'password', 'database') OR die('Could not connect because: '.mysqli_connect_error());
//function to dynamically change CSS
function getCSS($link, $tag){
$q = 'SELECT * FROM colors WHERE tag = "' . $tag . '"' ;
$r = mysqli_query($link, $q);
if(mysqli_num_rows($r)>0){ // check if there are results
while($row = mysqli_fetch_assoc($r)){
//echo '<pre>';
//print_r($row); // print the result array for debugging
//echo '</pre>';
echo $row['color'] . '<br />';
}
return $row;
} else { // if no result is found
echo 'No such tag';
}
}
// test it:
echo '<br />if tag is h1<br />';
getCSS($link, 'h1');
echo '<br />if tag is h2<br />';
getCSS($link, 'h2');
?>
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>
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.
<?php
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
if (!mysql_select_db('database'))
die("Can't select database");
// choose id 31 from table users
echo $id; //31
echo $name; //id31's name
echo $surname //id31's surname
echo $blablabla //id31's blablabla
mysql_close($link);
?>
Give this a shot:
$id = mysql_real_escape_string(31);
$result = mysql_query('SELECT * FROM `users` where `id` = ' . $id . ' LIMIT 1');
$row = mysql_fetch_assoc($result);
echo $row['id']; // 31
echo $row['name']; // name
// etc..
// If you wanted to output ALL the fields you could loop through
foreach($row as $field_name => $value) {
echo $field_name . ': ' . $value . '<br />';
}
// The output would look something like
// id: 31
// name: John Smith
// ...
Functions Used:
mysql_real_escape_string() - Escapes special characters in a string for use in an SQL statement
mysql_query() - Send a MySQL query
mysql_fetch_assoc() - Fetch a result row as an associative array