Please excuse my horrid coding and design aspect of this. I am not too concerned about the look of it as I am of how well it works.
I have 2 tables (Cars, Customers) in which both have the VIN columns. When I add a new car I put in a VIN, and when a customer purchases a vehicle, I select the VIN from a drop-down list that is populated in all cars with the field VSold is set to 'N'. That works great, the issue I have is that when I run the code below, it gives me multiple customer names. When I run a search query in that database for that table and exact VIN, there is only 1 customer that has that matching VIN (I made it UNIQUE), yet in my ugly code, it gives me a bunch of results, all the same car, just different customers. What am I doing wrong here? How can I clean this thing up?
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$VIN=$_POST['formVIN'];
$sql =
"SELECT
Cars.VIN, Cars.VYear, Cars.VMake, Cars.VModel,
Cars.VOdometer, Cars.VPurchasedPrice, Cars.VPurchasedDate,
Cars.VSold, Cars.VSoldPrice, Cars.VSoldDate, Cars.VSalesPerson,
Customers.CustFirst, Customers.CustLast
FROM
Cars, Customers
WHERE Cars.VIN='$VIN'";
mysql_select_db('dbCar2016');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "Information on record for the VIN provided:<br><br>";
echo "VIN:" . $row["VIN"] . "<br>";
echo "Year:" . $row["VYear"] . "<br>";
echo "Make:" . $row["VMake"] . "<br>";
echo "Model:" . $row["VModel"] . "<br>";
echo "Odometer:" . $row["VOdometer"] . "<br>";
echo "Purchased Price:$" . $row["VPurchasedPrice"] . "<br>";
echo "Purchased Date:" . $row["VPurchasedDate"] . "<br><br>";
if ($row["VSold"]=='Y') {
echo "This Vehicle sold.<br>";
echo "Price Sold:" . $row["VSoldPrice"] . "<br>";
echo "Date Sold:" . $row["VSoldDate"] . "<br>";
echo "Sales Person:" . $row["VSalesPerson"] . "<br><br>";
echo "It was sold to<br>";
echo "Customer Name:" . $row["CustFirst"] . " " . $row["CustLast"] . "<br>";
} else {
echo "This Vehicle has not sold yet.<br>";
}
echo "<p>VIN Successfully Searched</p>";
}
echo "<a href=vinlookup.php>Search Another VIN</a>";
mysql_close($conn);
?>
When I put a VIN of a vehichle not sold (VSold='N'), I don't have any issue. (I think...) I tried using a UNION between the tables, but I got even more mixed up.
Thanks ahead of time for the help!
UPDATE:
UPDATE
Cars SET VSold='Y',
VSoldPrice='$VSoldPrice',
VSoldDate='$CustDownDate',
VSalesPerson='$VSalesPerson'
WHERE
VIN='$VIN'
Is what I have on the page that I add customers to. It inputs all the customers information, (CustFirst, CustLast, etc.), to the table Customers. Thus no Customers.VIN will ever be filled out if there was no customer associated with any VIN (Cars.VIN).
If I understood correctly your problem (you have multiple queries returning and not only one), change this:
WHERE Cars.VIN='$VIN'
to this
WHERE Cars.VIN='$VIN' AND Cars.VIN = Customers.VIN
From what it looks like you're trying to do you should be using an inner to get info from both tables.
SELECT Cars.VIN, Cars.VYear, Cars.VMake, Cars.VModel, Cars.VOdometer, Cars.VPurchasedPrice, Cars.VPurchasedDate, Cars.VSold, Cars.VSoldPrice, Cars.VSoldDate, Cars.VSalesPerson, Customers.CustFirst, Customers.CustLast
FROM Cars
INNER JOIN Customers
ON Customers.vin = Cars.vin
WHERE Cars.VIN='$VIN'";
SELECT
Cars.VIN, Cars.VYear, Cars.VMake, Cars.VModel, Cars.VOdometer,
Cars.VPurchasedPrice, Cars.VPurchasedDate, Cars.VSold, Cars.VSoldPrice,
Cars.VSoldDate, Cars.VSalesPerson, Customers.CustFirst, Customers.CustLast
FROM
Cars, Customers
WHERE
Cars.VIN='$VIN'
Produces a cartesian product between cars and customers. That is, it returns all combinations of rows between the two tables. To avoid this, you need a join. If you will always have at least one sold car per customer (ie, it's a sales database), then use an inner join. If, however, you may sometimes have customers that have not bought a car, but still want all customers, then use a left join. This will cause all of the car columns to contain NULL if there's not a corresponding record.
SELECT
Cars.VIN, Cars.VYear, Cars.VMake, Cars.VModel, Cars.VOdometer,
Cars.VPurchasedPrice, Cars.VPurchasedDate, Cars.VSold, Cars.VSoldPrice,
Cars.VSoldDate, Cars.VSalesPerson, Customers.CustFirst, Customers.CustLast
FROM
Cars
LEFT JOIN Customers on Cars.VIN = Customers.VIN
WHERE
Cars.VIN='$VIN'
Additionally, look into using the mysqli library (or similar) and learn how to parameterize your queries so you can avoid dealing with SQL Injection later.
While all your answers did solve the multiple search results, it was giving me no results if the vehicle wasn't sold, hence no VIN associated with any customer. I decided to go about it through multiple search queries and IF statements. PROBABLY not the most efficient or cleanliness but it works great. Any code improvements are always welcome. Thank for all your guys help!
$formVIN = $_POST[formVIN]
sql1= SELECT * FROM Cars WHERE VIN=$formVIN
sql2= SELECT * FROM Customers WHERE VIN=$formVIN
$retval1=mysql_query( $sql1, $conn )
$retval2=mysql_query( $sql2, $conn )
if(! $retval1 ) {
die('No VIN information.' . mysql_error());
} else {
while($row1 = mysql_fetch_array($retval1, MYSQL_ASSOC)) {
echo "<p><b>Information on record for the VIN provided:</b></p>";
echo "VIN:" . $row1["VIN"] . "<br>";
echo "Year:" . $row1["VYear"] . "<br>";
echo "Make:" . $row1["VMake"] . "<br>";
echo "Model:" . $row1["VModel"] . "<br>";
if ($row1["VSold"]=='Y')
{
while($row2 = mysql_fetch_array($retval2, MYSQL_ASSOC)) {
echo "<p><b>This Vehicle sold.</b></p>";
echo "Price Sold:" . $row1["VSoldPrice"] . "<br>";
echo "Date Sold:" . $row1["VSoldDate"] . "<br>";
echo "Sales Person:" . $row1["VSalesPerson"] . "<br>";
echo "<p><b>It was sold to:</b></p>";
echo "Customer ID:" . $row2["CustID"] . "<br>";
echo "Customer Name:" . $row2["CustFirst"] . " " . $rowl["CustLast"] . "<br>";
}
} else
{
echo "<p><b>This Vehicle has not sold yet.</b></p><br>";
}
}
}
Like I said, probably not the most efficient way to go about it, but it works great. Thanks everyone!
Related
I'm creating a cart system and trying to find a way to have a simple button that once pressed deletes the corresponding row. However, I cannot seem to find a way to dynamically do this with while loop I currently have.
<?php
//connect to DB.
$con = mysqli_connect("localhost", "root", "", "books");
if(mysqli_connect_errno())
{
echo "Failed to connect to MySql: ". mysqli_connect_error();
}
$query = "SELECT * FROM cart WHERE customerID = '$_SESSION['id']'";
$result = mysqli_query($con, $query);
//creates a table for dumping the DB to, loops through the DB and posts the contents elegantly.
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['bookAuthor'] . "</td><td>" . $row['bookTitle'] . "</td><td>" . $row['bookPrice'] . "</td></tr>";
$totalprice += $row['bookPrice'];
}
echo "</table>";
echo "The total present price is: $".$totalprice;
//closes the conncection to the DB
mysqli_close($con);
?>
I've considered trying to put an echo query statement into the database and adding "$row['deletebutton']" to the while loop but I'm not sure that would necessarily work.
The easy way is to create a new page and send the message to this page to delete the item.
So, in the table you add a new column with a link
delete
And in the page you treat this value.
To expand on the comment posted to the question, you could add this to your row:
echo "<tr><td>" . $row['bookAuthor'] . "</td><td>" . $row['bookTitle'] . "</td><td>" . $row['bookPrice'] . "</td><td><input type='checkbox' name='remove[]' value='" . $row['ROW_ID'] . "' /></td></tr>";
And then with the data submitted in the form you could do something like this:
$query = "DELETE FROM cart WHERE ROW_ID IN (" . implode(',',$_POST['remove']) . ")";
Keep in mind to check the value of remove before using it in queries.
I'm trying to create a simple e-commerce system. First thing I did was select the rows with the same Order ID from mysql. My table looks like this:
Now, I'd like to know how I can group them into separate divs, it should look like this:
Here's my code:
$con = mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result2 = mysqli_query($con, "SELECT DISTINCT request_date, department_id FROM tbl_requests WHERE request_id=".$_GET['request_id']) ;
while($row2 = mysqli_fetch_array($result2)) {
echo "" . $row2['request_date'] . "<br/>";
echo "Order from Department " . $row2['department_id'] . "<br/>";
echo "<br/>";
echo "<hr/>";
echo "<br/>";
}
$result = mysqli_query($con,"SELECT * FROM tbl_requests WHERE request_id=".$_GET['request_id']);
while($row = mysqli_fetch_array($result)) {
echo "" . $row['request_details'] . "";
echo "<br/>";
}
I'm sorry if ever this question is incomplete, please feel free to ask me any more questions. Thank you in advance :)
You can check for every product in array using Javascript or jQuery(much easier).
This way you can check if your page does contain any existing div with that manufacture id (ie. #m_1055, #m_1040) or not.
If div does exist, append product in that div (in jQuery.append())
If not, then first append the div with that manufacture id to the document and then append the product to it.
i have simple db that it is filled by a form from a page, all is ok in the entry.
i have 2 fields in the database are: all_students and current_students filled by the user in the form that i want to calculate
the trick is that i am echoing only the latest db record in the output page.. to give me only the latest data inserted in the form...
now, i want to create a new field that give me the absent students automatically (all - current)
what i have tried, i read that i can NOT create a new calculated field in the db, it is not an excel, so i am trying to echo the calculation results of these 2 fields, to a new value that is the "absent students"
what you suggest? please help, here is my code
<?php
$con=mysqli_connect("localhost","root","PasswordHere","DBnameHere");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT id, class, all_students, current_students FROM students ORDER BY id DESC LIMIT 1");
while($row = mysqli_fetch_array($result))
{
echo "Class: " . $row['class'] . "<br>";
echo "All students: " . $row['all_studnets'] . "<br>";
echo "Current students: " . $row['current_studnets'] . "<br>";
echo "Absent students: " . $row['all_studnets'] . - . $row['current_studnets'] . " <br>";
}
mysqli_close($con);
?>
You only put dot (.) if you want to concatenate a string. Please remove the dot since you are subtracting.
echo "Absent students: ";
echo floatval($row['all_studnets']) - floatval($row['current_studnets']);
echo "<br>";
Try this line
echo "Absent students: " . $row['all_studnets'] - $row['current_studnets'] . " <br>";
Insted of this
echo "Absent students: " . $row['all_studnets'] . - . $row['current_studnets'] . " <br>";
I hope someone can help me with this?
I have a Joomla installation running and the website looks and works great.
Here's the problem, the website is for a car dealership, which means they need to display a list of their stock on the floor.
They are using a custom system to manage their stock and this system saves the data to a MS Access database.
I got it to work to a point where I can display a table from the database. (http://www.autodeal.co.za/newsite/used-car-sales-south-africa).
Now when someone clicks on the model, which is a link that will take them to another page which displays only the information relevant to the selected model.
That's what I can't figure out. The link works fine and it takes me to the page that I want, but it doesn't display the data like it's supposed to.
Please see the code below for connecting to the database and displaying the results:
<?php
$dbName = "F:/Domains/autodeal/autodeal.co.za/wwwroot/newsite/db/savvyautoweb.mdb";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
// This is the query
// You have to have each column you select in the format tableName.[ColumnName]
$sql = "SELECT Make, Model, Year, Price, SpecialPrice, Branch, StockNO FROM Vehicle ORDER BY Make";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
echo "\t" . "<tr>\n";
echo "\t" . "<th>Make</th><th>Model</th><th>Year</th><th>Price</th><th>Special Price</th><th>Location</th><th>Stock Number</th>" . "\n";
while (odbc_fetch_row($rs))
{
$make = odbc_result($rs, Make);
$model = odbc_result($rs, Model);
$year = odbc_result($rs, Year);
$price = odbc_result($rs, Price);
$specialPrice = odbc_result($rs, SpecialPrice);
$branch = odbc_result($rs, Branch);
$stockNo = odbc_result($rs, StockNO);
echo "\t" . "<tr>\n";
echo "\t\t" . "<td>" . $make . "</td><td><a href=http://www.autodeal.co.za/newsite/selected-vehicles>" . $model . "</a></td><td>" . $year . "</td><td>" . $price . "</td><td>" . $specialPrice . "</td><td>" . $branch . "</td><td>" . $stockNo . "</td>\n";
echo "\t" . "</tr>\n";
}
odbc_free_result($rs);
odbc_close($conn);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
?>
Please see the code below to display a specific vehicle information from the table based on a selection made from the above script.
<?php
$dbName = "F:/Domains/autodeal/autodeal.co.za/wwwroot/newsite/db/savvyautoweb.mdb";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
// This is the query
// You have to have each column you select in the format tableName.[ColumnName]
$selected_id = intval($_GET['Id']);
$sql = "SELECT Id, Make, Model, Year, Price, SpecialPrice, Branch, StockNO, MainPic FROM Vehicle WHERE Id = Id";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
$id = odbc_result($rs, Id);
$make = odbc_result($rs, Make);
$model = odbc_result($rs, Model);
echo $make;
echo $model;
$image_path_main = "<img src=db/vehicleImages/" . $mainPic . "/>";
echo "this is a test";
odbc_free_result($rs);
odbc_close($conn);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
?>
EDIT So I've updated the above code based an answer received, but the individual records aren't displayed. I printed a test line and that works fine, so that tells me that there's an issue with the query? The thing is, the query works fine to display all the records in a table, but I need to display a single record when that record has been clicked.
Furthermore, the $mainPic variable above is referencing the image name from the database. The actual image isn't saved in the database; it's in a different location. I assume I need to create a variable with the actual path of the image and use the reference variables above to display the image, but it's not working.
So to recap, I need some help displaying all information from the database based on a selection.
For example: in the table, I select 323i. On a new page, I need to display all the information that's in the database about the 323i on a new page.
Is that doable and if so, could anyone please assist me in this matter.
Thank you very much in advance.
You are not using given ID parameter in your query:
$sql = "SELECT ... FROM Vehicle WHERE Id = Id ORDER BY Make";
you need to get $ID from user and place it into the query like:
$id = intval($_GET['id']); // assuming it is an integer
$sql = "SELECT ... FROM Vehicle WHERE Id = $id; // no need to order
I'm designing a website for a neighbor for a potential restaurant he wants to open. I need to create a page for testimonials/review. I'd like to code it so that the number of stars is in a SQL, I'm just not sure how to do it.
Essentially what I'm looking for is a way to determine the integer of the ratings field (1-5) and for each number, display a star image.
So:
if rating = 1, display star.png once
if rating = 2, display star.png twice
...
if rating = 5, display star.png five times
I'm just not sure how to write the code to do so.
The website is being written in PHP and CSS. I'd like to avoid JQuery, Javascript, .NET, and so forth, as I'm not as familiar with them and will be the one keeping the site up to date.
Here's what I've got so far, but it's not working right, and I get a syntax error:
$result = mysqli_query($con,"SELECT * FROM Reviews");
while($row = mysqli_fetch_array($result))
{
IF (Rating = "1"()){
echo '<img src="star.png">' . }
ELSE IF (Rating = "2"()){
echo '<img src="star.png"><img src="images/star.png">' . }
Else IF (Rating = "3"()){
echo '<img src="star.png">star.png"><img src="images/star.png">' . }
ELSE IF (Rating = "4"()){
echo '<img src="star.png"><img src="images/star.png">star.png"><img src="images/star.png">' . }
ELSE
echo '<img src="star.png"><img src="images/star.png">star.png"><img src="images/star.png"><img src="images/star.png">' .
"<br/> <b>" .
$row['Name'] .
"</b> <em>" .
$row['City'] . $row['State'] . $row['Country'] . "</em><br/>" .
$row['Review'] . "<br/> <hr> <br/>"
}
?>
Use a select statement to get the ratings for a place from your database.
Store the result in a php variable (lets call it $rating)
Use php logic to output number of stars (in html obviously) based on value of $rating.
Hope that helps :)
I would recommend 3 tables for this idea.
Users Table
UserRatings Table
Dish Table
Users table is used to store just that. User information. Possibly a username, password, first name, last name for example. The table should have a primary key. Call it UsersID. It should auto increment itself and be unique for every row.
The Dish table is next. Put a dish name in it. It should have a primary key as well. Call it DishID.
Lastly is the UserRatings table will store UserRatingsId, Rating, InsertTimeStamp, UpdateTimeStamp.
Use a loop to output your HTML based on your rating.
$rating = 4; //Figure this out in your script and set accordingly
for($i = 0; $i < $rating; $i++) {
echo '<img src="star.png" />';
}
Should print out four stars for you.
Help from a friend:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$starCount = 0;
$result = mysqli_query($con,"SELECT * FROM Reviews");
while($row = mysqli_fetch_array($result)) {
$starCount = $row['Rating'] ;
while ($starCount > 0) {
echo '<img src="images/star.png">';
$starCount -- ;
}
$starCount = 0;
echo "<br/> <b>" . $row['Name'] . "</b> - <em>" .
$row['City'] .", ". $row['State'] ." ". $row['Country'] . "</em><br/>" .
$row['Review'] . "<br/> <hr> <br/>" ;
}
?>
$number=$row->rating ;
$middle="";
$first="<td width='200' align='left'>";
for($x=1;$x<=$number;$x++) {
$middle=$middle.img($fullimage_properties);
}
if (strpos($number,'.')) {
$middle=$middle.img($halfimage_properties);
$x++;
}
while ($x<=5) {
$middle=$middle.img($blankimage_properties); ;
$x++;
}
echo $last=$first.$middle."</td>";