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.
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've tried to find an answer to this problem, but I can't.
I have a 3 table format mqsql database.
I use 1 table to add all of the product information, CarpetInfo,
1 Table to list my categories, CarpetCategories,
and 1 Table to add categories to the products, CarpetCategorySort.
My CarpetCategorySort table has 3 columns, Manufacturer, Style, CategoryID.
Example would be Manufacturer = Aladdin, Style = Alma Mater, CategoryID = 14/ 15/ 18/ 19/ 20/ 21/ 67/
My CarpetCategories Table has 2 Columns CategoryID and Category.
2 Examples would be CategoryID = 14, Category = Commercial &
CategoryID = 15, Category = Commercial Loop
I can only get the code to work when I type in Commercial into the $category variable below. The code will not work if I type Commercial Loop into the $category variable. It's like it will only pull in the first number 14 and all of the others are ignored. The pricing order and everything else works right, just not the CategoryID part.
Here is my code.
<?php $mill = "Aladdin"; $category = "Commercial Loop";
$order = mysqli_query($con, "
SELECT * FROM CarpetInfo JOIN CarpetCategorySort USING (Manufacturer, Style)
JOIN CarpetCategories USING (CategoryID)
WHERE Manufacturer='$mill' AND Category LIKE '%$category%'
order by Price = 0, Price asc,
Style asc");
include($_SERVER['DOCUMENT_ROOT'].'/includes/pricing/carpet-order-test.htm');?>
Any help is greatly appreciated!
That's a backward way of handling things, a field with several datapoints smooshed together like that really never has any justification for existence. I'd list the carpets in one table, list the categories in another, and finally list cross-references of both in another table, where you get a many-to-one relationship at both ends.
You need an actual category table only if you think it's going to take so much room to give duplicate info for each category and/or you can't control user input for categories (like you aren't just using a pulldown to give a name choice).
Something like:
CREATE TABLE IF NOT EXISTS `carpets` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`abbrev` varchar(10),
`description` varchar(250),
[...]
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `carpet_categories` (
`id` int(11) NOT NULL,
`carpet_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
[...]
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `carpet_category_info` (
`id` int(11) NOT NULL,
`price-per-sqf` int(11) NOT NULL,
`name` varchar(50),
[...]
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
then all your joins become simple, and fast.. And accurate.
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.
i have two tables in my database. One name jokes and the other named category.
jokes
CREATE TABLE `jokes` (
`joke_id` int(11) NOT NULL AUTO_INCREMENT,
`joke` varchar(1024) NOT NULL,
`category_id` int(11) NOT NULL,
PRIMARY KEY (`joke_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
category
CREATE TABLE `category` (
`category_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(51) NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
and i was wondering what the query would be to find the category name of a joke so it can be displayed on the home page like title:"Celebrity Joke" joke:"Miley Cyrus is a joke" and so on..
Would anybody be able to help me out on this problem, im guessing it will be a query/string assigned to a variable named $category_name which will reference both tables, but again, im not too sure how to go about it.
Try this first joining two tables:
SELECT
* //You can filter more your columns here
FROM
jokes
LEFT JOIN category ON
jokes.category_id = category.category_id
Now after this statement you can add a WHERE CLAUSE and it could be something like this
WHERE category.category_name like '%Miley%'
Means you will retrieve records having a category that has name of Miley
If you were going to do this with all jokes/categories it would look like:
SELECT * FROM jokes UNION SELECT * FROM category
However if you wanted to do a single joke you could just use the answer posted by Drixson. IF you wanted all the jokes from one category you would do:
SELECT * FROM jokes WHERE category_id=CATEGORY_ID
Some PHP you could use to display jokes from each category:
//Cat ID, using 1 for example
$category = 1
//Query
$query = "SELECT * FROM jokes WHERE category_ID=:cat";
//Establish PDO, prepare, apply parameter, execute, fetch data
$search = new PDO("mysql:host=HOST;dbname=DB",USERNAME, PASSWORD);
$runQuery = $search->prepare($query);
$search->bindParam(':cat', $category, PDO::PARAM_INT);
$search->execute();
$results = $search->fetchAll();
//For every row display joke_id and the joke
foreach($results as $joke){
echo $jokes["joke_id"] . " - " . $jokes["joke"];
}
//Kill
$results = null;
Hope it helps. PDO is pretty easy to pick up so if you need anymore help just search for a PDO tutorial on Google.
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';