I have a table with the following structure and i want to get the sum of all the times for a certain album_id & disc. I found this http://board.phpbuilder.com/showthread.php?10326769-RESOLVED-time-help and it looked somewhat good (the first snippet of code in the first answer), but I cant figure out how to work it ith mysql...
Table Structure:
CREATE TABLE IF NOT EXISTS `tracks` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`artist_id` int(255) NOT NULL,
`album_id` int(255) NOT NULL,
`disc` int(3) NOT NULL,
`track_no` int(3) NOT NULL,
`title` varchar(255) NOT NULL,
`length` time NOT NULL,
`size` decimal(20,1) NOT NULL,
`plays` int(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `artist_id` (`artist_id`,`album_id`,`disc`,`track_no`,`title`)
) ;
Any help is greatly appreciated. I'm a noob!!!
Maybe this will do.
SELECT album_id, disc, SEC_TO_TIME(SUM(TIME_TO_SEC(length))) AS formatTime
FROM tracks
GROUP BY album_id, disc
HAVING album_id=id AND disc=disc
Alternative for only a certain album and disc:
SELECT album_id, disc, SEC_TO_TIME(SUM(TIME_TO_SEC(length))) AS formatTime
FROM tracks
WHERE album_id=id AND disc=disc
//this is the album we want
$album = 24;
//grab all the track lengths and plays from our album
$query = '
SELECT length, plays
FROM tracks
WHERE album_id = "'.$album.'";
//do our mysql query
$result = mysql_query($query) or die(mysql_error());
//now for every result do somthing like add the length of the songs or play count
$length = null;
$plays = null;
while ($row = mysql_fetch_assoc($result)) {
$length = $length + $row["length"];
$pays = $plays + $row["plays"];
}
//echo data to user
echo 'The total lenth of this albums is:'.$length.'mins';
echo 'this ablum as been played:'.$plays.'times';
Related
I'm a newbie in PHP. I hope someone can help me. before that sorry my english's bad.
I want set kd_transaksi base on date and id from another table. when people booking, system automatically set kd_transaksi.
$tgl_pesan = date("Ymd");
$cek = mysqli_query($conn, "SELECT max(kd_booking) AS kode FROM booking WHERE kd_booking LIKE '$tgl_pesan%'");
$row = mysqli_fetch_array($cek);
$kdMax = $row['kode'];
$nourut = substr($kdMax, 8, 4);
$nourut++;
$char = "BO";
$kd_transaksi = $char.$tgl_pesan.printf('%04s', $nourut);
$kd_booking = mysqli_insert_id($conn);
$book = "INSERT INTO detail_booking (kd_booking,kd_transaksi,total_bayar) VALUES ('".$kd_booking."','$kd_transaksi',$total_bayar')";
$ok = mysqli_query($conn,$book);
if ($ok) {
header('location:../mybooking.php');
} else{
mysqli_close($conn);
}
but result in query $cek is NULL.
$cek = mysqli_query($conn, "SELECT max(kd_booking) AS kode FROM booking WHERE kd_booking LIKE '$tgl_pesan%'");
how do I fix it?
booking table
CREATE TABLE `booking` (
`kd_booking` int(11) NOT NULL,
`id_user` int(11) NOT NULL,
`kd_paket` int(11) NOT NULL,
`jml_org` int(11) NOT NULL,
`tgl_pesan` date NOT NULL,
`tgl_wisata` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
What i want is
If someone booking today and get kd_booking 21, then the output would be : BO2018120521.
First of all, you have something wrong with your CREATE TABLE. When you create a table you should have an AUTOINCREMENT primary key, this is your id. So it would be something like this:
CREATE TABLE `booking` ( `id` INT NOT NULL AUTO_INCREMENT , `id_user` INT(11) NOT NULL , `kd_paket` INT(11) NOT NULL , `jml_org` INT(11) NOT NULL , `tgl_wisata` DATE NOT NULL , `tgl_pesan` DATE NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;
As i can se you have two errors:
Date should be like date('Y-m-d') http://php.net/manual/en/function.date.php
You're trying to insert an int value like '".$kd_booking."' when that just works for strings.
Hope it helped.
I have 2 tables in SQL first one named cars
`cars` (`car_id` int(100) NOT NULL,`car_first_registration` text NOT NULL, `car_brand` int(11) NOT NULL, `car_profile_image` text NOT NULL, `car_cat` int(11) NOT NULL, `car_price` decimal(10,0) NOT NULL, `car_vin` char(20) NOT NULL, `car_mileage` char(20) NOT NULL, `car_seats` int(11) NOT NULL, `car_gearbox` text NOT NULL, `car_ext_color` char(30) NOT NULL, `car_int_color` char(20) NOT NULL, `car_desc` text NOT NULL, `car_stock` varchar(255) NOT NULL, `car_keywords` text NOT NULL, `car_visibility` tinyint(1) NOT NULL, `car_ref` char(8) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1
`car_brands` (`brand_id` int(100) NOT NULL,`brand_title` text NOT NULL) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=latin1;
In cars table I can insert cars with many information that fits the columns, but i have one problem that car_brand in cars table is store as a value,this value is taken from car_brands :preloaded brands , and so when i insert a car i choose from the brands that are in car_brands, and car_brands has 2 columns id and title , but the problem is when i want to get the cars the car_brand is stored as a number that is equal to the ID in car_brands
For exemple I have a car who's brand is BMW and stored as ID=4 in car_brands table so it will be stored as a value of 4 in car_brand in cars table. I want to have this value on GET method to display the products as a text (BMW) NOT 4
That is my display code of cars please tell me what to correct so i can display the name not the ID
NB: don't confuse between car_brands and car_brand , car_brands is a table and car_brand is a column in cars table
Thanks a lot really:):):)!!!
<?php
function getCars(){
if(!isset($_GET['car_categories'])){
if(!isset($_GET['car_brands'])){
global $con;
$car_visibility = isset($_POST['car_visibility']);
$get_pro = "select * from cars where car_visibility= true";
$run_pro = mysqli_query($con, $get_pro)
or die("Error: ".mysqli_error($con));
$i = 0;
while($row_pro=mysqli_fetch_array($run_pro)){
$i++;
$car_id = $row_pro['car_id'];
$car_first_registration = $row_pro['car_first_registration'];
$car_brand = $row_pro['car_brand'];
$car_profile_image = $row_pro['car_profile_image'];
$car_cat = $row_pro ['car_cat'] ;
$car_price = $row_pro['car_price'];
$car_vin = $row_pro['car_vin'];
$car_mileage = $row_pro['car_mileage'];
$car_seats = $row_pro['car_seats'];
$car_gearbox = $row_pro['car_gearbox'];
$car_ext_color = $row_pro['car_ext_color'];
$car_int_color = $row_pro['car_int_color'];
$car_desc = $row_pro['car_desc'];
$car_stock = $row_pro['car_stock'];
$car_keywords = $row_pro['car_keywords'];
$car_visibility = $row_pro['car_visibility'];
$car_ref = $row_pro['car_ref'];
$get_brands ="SELECT * FROM car_brands";
$fetch_brands = "SELECT cars.car_id , cars.car_first_registration , cars.car_brand, cars.car_profile_image, cars.car_cat , cars.car_price , cars.car_vin, cars.car_mileage , cars.car_seats , cars.car_gearbox , cars.car_ext_color, cars.car_int_color, cars.car_desc , cars.car_desc , cars.car_stock , cars.car_keywords , cars.car_visibility , cars.car_ref , car_brands.brand_id
FROM cars
INNER JOIN car_brands
ON cars.car_brand=car_brands.brand_id";
echo "<div class='single_product'>";
echo "<h1><a href='details.php?car_id=$car_id' id='product_title'>$car_brand . $car_cat . $car_first_registration</a></h1>";
echo "<img src='admin_area/Car Profiles/$car_profile_image' />
<h2>$ $car_price</h2>
</div>";
}
}
}
}
?>
<?php getCars();?>
You already know how to join. So, make it simple and do all you want with one query.
Change the first query to this:
SELECT * FROM cars
INNER JOIN car_brands
ON cars.car_brand=car_brands.brand_id AND cars.car_visibility = 1
You don't need any query more.
Wherever you need to show the brand name of the car, you can use $row_pro['brand_title']. So, you can change this:
$car_brand = $row_pro['car_brand'];
to this:
$car_brand_id = $row_pro['car_brand'];
$car_brand_name = $row_pro['brand_title'];
By the way, I recommend you read about the relations and indexes to make a better DataBase structure.
Okay so now its display results like 3 times in a row
$user_apps = mysql_query("SELECT a.name,a.download_url FROM user_apps as ua LEFT JOIN
apps as a ON (ua.app_id=a.app_id)
WHERE ua.user_id='$user_id'") or die(mysql_error());
while($raw = mysql_fetch_array($user_apps)){
$name = $raw['name'];
$url = $raw['download_url'];
echo $name;
echo "<br />";
echo $url;
}
Database Table Structure(since I am new to the site and did not know how to display the table structure I just exported the sql)
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
CREATE TABLE IF NOT EXISTS `user_apps` (
`user_id` int(11) NOT NULL,
`app_id` int(11) NOT NULL,
KEY `user_id` (`user_id`,`app_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `apps` (
`app_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`description` text NOT NULL,
`icon` varchar(255) NOT NULL,
`download_url` varchar(255) NOT NULL,
`default` int(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`app_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
I'v tried different Join types but that does not seem to work.
Used the join query for get the result check bellow example query
$user_apps = mysql_query("SELECT DISTINCT a.name,a.download_url FROM user_apps as ua LEFT JOIN apps as a ON (ua.app_id=a.app_id) WHERE ua.user_id='$user_id'") or die(mysql_error());
while($raw = mysql_fetch_array($user_apps)){
$name = $raw['name'];
$url = $raw['download_url'];
echo $name;
echo $url;
}
change the join type as per your requirement. the above query for only example
INNER JOIN: Returns all rows when there is at least one match in BOTH
tables
LEFT JOIN: Return all rows from the left table, and the matched rows
from the right table
RIGHT JOIN: Return all rows from the right table, and the matched
rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
more about join click here
AND also check this http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/
You have used single quotes in query at user_id='$user_id' .
Are you sure your user_id is char, varchar or text? Just print_r($user_apps) and check it has any records or not? If user_id is int,tinyin than remove single quote.
my table:
CREATE TABLE IF NOT EXISTS `the_kho_chi_tiet_with_id` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ngay_thang` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`ma_phieu` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`id_san_pham` int(11) NOT NULL,
`id_kho` int(11) NOT NULL,
`khoi_luong_nhap` double NOT NULL,
`so_luong_nhap` int(11) NOT NULL,
`khoi_luong_xuat` double NOT NULL,
`so_luong_xuat` int(11) NOT NULL,
`khoi_luong_ton` double NOT NULL,
`so_luong_ton` int(11) NOT NULL,
`kho_du_tru` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
PHP code:
$sql = "SELECT so_luong_ton, khoi_luong_ton, kho_du_tru FROM the_kho_chi_tiet_with_id WHERE id_kho = $id_kho and id_san_pham = $id_san_pham ORDER by id DESC LIMIT 1";
$command=$connection->createCommand($sql);
$dataReader=$command->queryAll();
if($dataReader!=null)
{
foreach($dataReader as $row)
{
.................
}
}
**Get a record with maxid and condition in mysql in yii, *but sometime it get second record* !?**
Please check with the below, hope it works!..if not please tell...
$id_kho=373;//sample value declaration
$id_san_pham=1;//sample value declaration
$select="select max(id) as id,so_luong_ton, khoi_luong_ton, kho_du_tru from
the_kho_chi_tiet_with_id where users_ref_id=".$id_kho." and
status=".$id_san_pham;
$command = Yii::app()->db->createCommand($select)->queryRow();
$Maxid=$command['id'];
$so_luong_ton=$command['so_luong_ton'];
$khoi_luong_ton=$command['khoi_luong_ton'];
$kho_du_tru=$command['kho_du_tru'];
I think, the problem is conflict. It mean that when I get record have max_id, and then before i insert new record, having another process insert new record was inserted.
if such cases happen, so how to handle to fix above problem?
My solution:
$lock = $connection->createCommand('LOCK TABLES `the_kho_chi_tiet_with_id` READ');
$lock->execute();
$sql = "SELECT so_luong_ton, khoi_luong_ton, kho_du_tru FROM the_kho_chi_tiet_with_id WHERE id_kho = $id_kho and id_san_pham = $id_san_pham ORDER by id DESC LIMIT 1";
$command=$connection->createCommand($sql);
$dataReader=$command->queryAll();
if($dataReader!=null)
{
foreach($dataReader as $row)
{
.................
}
}
//Insert new record here
TheKhoChiTietWithId::model()->InsertNewRecord(1,300,1,333,1);
$unlock = $connection->createCommand('UNLOCK TABLES');
$unlock->execute();
I lock table to keep no other session work to this table.
I have two tables one containing a selection of values in different categories and the other ‘master’ table referencing the text values by the first primary key.
Table 1
CREATE TABLE IF NOT EXISTS `defaultvalues` (
`default_ID` int(11) NOT NULL AUTO_INCREMENT,
`columnName` varchar(100) NOT NULL,
`defaultValue` varchar(100) NOT NULL,
PRIMARY KEY (`default_ID`),
UNIQUE KEY `columnName` (`columnName`,`defaultValue`)
)
Table 2
CREATE TABLE IF NOT EXISTS `master` (
`master_ID` int(11) NOT NULL AUTO_INCREMENT,
`size` int(11) NOT NULL,
`madeby` int(11) NOT NULL,
`type` int(11) NOT NULL,
`colour` int(11) NOT NULL,
`notes` text NOT NULL,
`issueDate` datetime NOT NULL,
`ceMark` text NOT NULL,
`batchNumber` text NOT NULL,
PRIMARY KEY (master_ID)
)
The master.size for each row is a P.key in the defaultvalues table.
E.g. master.colour = 234, 234=defaultvalues.defaultValue = ‘red’
E.g. master.size = 345, 345=defaultvalues.defaultValue = ‘small’
Now I would like to run a query that returns the ‘master’ table with text values in columns colour, size, type, madeby from ‘defaultvalues. defaultValue’ and ready for further processing.
I have been trying with sub queries and temp tables but I can’t get it to work
The current system relies on PHP and multiple queries and building arrays.
There has to be a more elegant solution.
I hope this makes sense.
Any hints or advice much appreciated.
Dave
You'll need to join the master table to the defaultvalues table multiple times. Something like this:
SELECT m.*, d.defaultvalue as sizevalue, d2.defaultvalue as colorvalue...
FROM master m
JOIN defaultvalues d ON m.size = d.default_id
JOIN defaultvalues d2 ON m.color = d2.default_id
...
What i did in the end.... while it works I am still not happy. There must be something better...
SELECT m.*,
(SELECT defaultValue FROM defaultvalues WHERE default_ID = m.colour) AS myColour ,
(SELECT defaultValue FROM defaultvalues WHERE default_ID = m.size) AS mySize
FROM master m
WHERE m.master_ID = 1;