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>";
Related
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!
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 have a MYSQL table containing tournament data for players. Each player has stats like games_won, games_lost, etc. I am trying to display this information in a table.
My PHP code looks like this:
//Connecting to $db
//...
//Store table data into array
$result = mysqli_query($db, "SELECT * FROM ladder");
while($row = mysqli_fetch_array($result)) {
echo $row['id'] . " " . <a href=$row['link']$row['username']</a> . " " . $row['tourney_wins'] . " " . $row['game_wins'] . " " . $row['game_losses'] . " " . $row['last_played'];
echo "<br>";
I get an error (Unexpected "<") on
<a href=$row['link']$row['username']</a>
I am trying to display each username in the table as a hyperlink to their respective profile on another site. Can anyone give me a correction? Thanks!
This is how it should be quoted (assuming I interpreted how you wanted the link properly):
//Connecting to $db
//...
//Store table data into array
$result = mysqli_query($db, "SELECT * FROM ladder");
while($row = mysqli_fetch_array($result))
{
echo( $row['id']." <a href='".$row['link']."'>".$row['username']."</a> ".$row['tourney_wins']." ".$row['game_wins']." ".$row['game_losses']." ".$row['last_played'] );
echo("<br>");
}
Change
<a href=$row['link']$row['username']</a>
to
"<a href=$row['link']$row['username']</a>"
You forgot to quote your html:
echo $row['id'] . " " . <a href=$row['link']$row['username']</a> . " " ...snip...
^--here ^--here
Since it's not quoted, PHP is interpreting it <a as concatenate less than undefined constant 'a', which makes no sense.
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>";
I'm printing all the data from one of the tables in my database using by using the mysql_fetch_query() to make an array and then the while function to print it.
The only thing is, it is skipping the first record and going straight to printing record 2. Record 1 does exist in the table, and is named as such.
Is there something I'm missing or need to add?
mysql_connect("$host", "$username", "$db_password")or die("cannot connect");
$data=mysql_query("SELECT * FROM users")or die(mysql_error());
$info=mysql_fetch_array($data);
while($info = mysql_fetch_array($data)){
echo "<br />";
echo "Record id: <strong>" . $info['id'] . "</strong>";
echo "<br />";
echo "Visit time and date: <strong>" . $info['visitDate'] . "</strong>";
echo "<br />";
echo "Previous destination: <strong>" . $info['cameFrom'] . "</strong>";
echo "<br />";
echo "Browser used: <strong>" . $info['browser'] . "</strong>";
echo "<br />";
echo "Location of user: <strong>" . $info['location'] . "</strong>";
echo "<p> </p>";
}
remove this line before while loop:
$info=mysql_fetch_array($data);
This will fetch the first record, and when you start while loop is starts from second row because you call mysql_fetch_array() again.
$info=mysql_fetch_array($data);
while($info = mysql_fetch_array($data)){
Leave only the condition, because you make one fetch before the loop, which is the first skipper row
you have called mysql_fetch_array() two times
**$info=mysql_fetch_array($data);
while($info = mysql_fetch_array($data))**
so your first record is already fetched with first call to mysql_fetch_array()
just remove first call and it will work ok.