How to round mysql column in a table output - php

I need to round a result of a SQL round in a table array output. I can't figure out the syntax...
$result = mysql_query("SELECT `Energ_Kcal`*`yield`*`qty` AS `cal` FROM allinnot a
WHERE `own_id` = $user->id");
echo "<tr><td>" . $row['Shrt_Desc'] . "</td><td> " . $row['desc'] . "</td><td>" . $row['cal'] . " cal</td></tr>";
cal returns a value with many numerals beyond the decimal. I just need it to show a whole rounded integer. I tried ROUND(), but I must be putting it in the wrong place.

general syntax
ROUND( expression, 2 )

The ROUND should go around the values, try this:
$result = mysql_query("SELECT ROUND(`Energ_Kcal`*`yield`*`qty`,2) AS `cal` FROM allinnot a
WHERE `own_id` = $user->id");
echo "<tr><td>" . $row['Shrt_Desc'] . "</td><td> " . $row['desc'] . "</td><td>" . $row['cal'] . " cal</td></tr>";

You could also check out PHP's round() or, possibly from your description int_val().

Related

How to echo a letter multiple times, changing more then one variable in it for each new print?

Hello all! This is my first question in stackoverflow so I hope I follow the rules good enough. :)
For my PHP class I have an exercise that makes it difficult for me: Text with about 4 variables in it, all are stored in arrays (one array for each variable, 3 values for each variable).
Position [0] of each array goes in the first echo text, position [1] of each array goes in the second text and so on.
How to echo the text 3 times using all values stored in the array? In the code I must use the main text only 1 time.
$u_name = array('student' => 'Joe','lecturer' => 'Kate', 'assistant' => 'Martin');
$course_name = array('PHP', 'CSS', 'HTML');
$role = array('student', 'lecturer', 'assistant');
echo "Hi," . $u_name['student'] . "! You've been approved to take part in course " . $course_name[0] . " as a " . $role[0] . ". The course " . $course_name[0] . " will last for two days.";
echo "<br>";
echo "Hi," . $u_name['lecturer'] . "! You've been approved to take part in course " . $course_name[1] . " as a " . $role[1] . ". The course " . $course_name[1] . " will last for two days.";
echo "<br>";
echo "Hi," . $u_name['assistant'] . "! You've been approved to take part in course " . $course_name[2] . " as a " . $role[2] . ". The course " . $course_name[2] . " will last for two days.";
This is what I did by myself, but as you see in the code I have 3 times the main text.
Thank you in advance.
Normally you go trough arrays with some type of a loop.
To name a few types of loops:
for
while
foreach
In this case the perfect fit is a foreach loop.
It simply goes through each element of the array, but because you have a associative array and two indexed array you also need a counter.
$counter = 0;
foreach($u_name as $key=>$value){
echo "Hi, " . $value . "! You've been approved to take part in course " . $course_name[$counter] . " as a " . $role[$counter] . ". The course " . $course_name[$counter] . " will last for two days.";
echo "<br>";
$counter++;
}
If still are any questions left, don't mind to ask.

Showing a limited number of mysqli_fetch_assoc array

I want to create an array with the help of MYSQL and display it the following way:
while ($array = mysqli_fetch_assoc($res))
{
echo $array["first_name"] . ", "
. $array["last_name"] . ", "
. $array["personal_id"] . ", "
. $array["salary"] . ", "
. $array["birthday"] . "<br />";
}
To improve usability, I only want to display 10 results, put a link to the next 10 results at the bottom and display these on another page.
How do I have to change the while-condition in order to only display the first 10 results of my result?
I tried searching for a solution but I couldn't find anything that fits my needs, so any help is appreciated!
Thanks in advance!
Check offset and limit conditions in mysql.
Example: to show 16 - 26 records from result query.
$sql = "SELECT * FROM Table LIMIT 10 OFFSET 15"
If what you want is just a way to break out of the loop after the first 10 results.
$counter = 1;
while (($array = mysqli_fetch_assoc($res)) || ($counter < 10))
{
echo $array["first_name"] . ", "
. $array["last_name"] . ", "
. $array["personal_id"] . ", "
. $array["salary"] . ", "
. $array["birthday"] . "<br />";
$counter++;
}

Assigning autonumber to HTML form entry

I have searched everywhere, but nothing I find seems to help solve this. I have a html web form (in a PHP document) that writes data to a CSV file, and below the form is a table that filters the CSV data back in based on a key word. I have no problems with my existing code for that part. However, I need to have an auto-number function that assigns a number to each form. I need help on even where to start. I'm still relatively new to coding, so any help would be great.
Edit: Here is the code I use to write my data to the csv file.
if($_POST['formSubmit'] == "Submit")
{
$fs = fopen("fixturerequests.csv","a");
fwrite($fs,$varFixNum . ", " . $varRequester . ", " . $varDept . ", " . $varSupervisor . ", " . $varDesc . ", " . $varParts . ", " . $varWC . ", " . $varAddinfo . ", " . $varDateReq . ", " . $varDateNeed . ", " .$varStatus . "\n");
fclose($fs);
header("Location: successfullysubmitted.php");
exit;
}
Any guidance would be excellent. Thank you.
You can use this function
function next_available_form_id(){
$rows = file('fixturerequests.csv'); //put our csv file into an array
if(empty($rows)) return 1; //if our csv is empty we start from 1
$data = str_getcsv(array_pop($rows)); //array_pop gets the last row
return $data[0]+1; //we get first field and add 1 to it
//Just use the field where you store the form number
//e.g if you store the form number in the
//4th field replace $data[0] with $data[3]
}
Based on the code you provided you can use the function I provided to get the next form_id before storing it in the csv file.Just make this modification to your code after opening the csv file :
$fs = fopen("fixturerequests.csv","a");
$form_id=next_available_form_id(); //ADD THIS to get the next available id
//And insert $form_id as the first field in your csv file
fwrite($form_id,$fs,$varFixNum . ", " . $varRequester . ", " . $varDept . ", " . $varSupervisor . ", " . $varDesc . ", " . $varParts . ", " . $varWC . ", " . $varAddinfo . ", " . $varDateReq . ", " . $varDateNeed . ", " .$varStatus . "\n");
Notice:
Of course since the csv you have now does not have form_id as the first field you should either create your csv file from scratch or add form numbers in your existing records.In the example I use awk to do that:
awk '{printf "%d,%s\n", NR, $0}' < fixturerequests.csv

Random number insert mySQL not working

Hey all i am created 2 random numbers like so:
$firstlink = intval(mt_rand(100, 999) . mt_rand(100, 999) . mt_rand(1, 9) . mt_rand(100, 999)); // 10 digit
$secondLink = intval(mt_rand(1000, 999) . mt_rand(1, 999) . mt_rand(10, 99) . mt_rand(100, 999));
And this is my insert code:
$result = mysql_query("INSERT INTO userAccount
(Category,Fname,LName,firstlink,secondLink,AccDate)
VALUES ( '" . $cat . "',
'" . $fname . "',
'" . $lname . "',
" . $firstlink . ",
" . $secondLink . ",
'" . date('Y-m-d g:i:s',time()). "');");
It has no errrs and it places the data into the mysql database. However, its always the same number for BOTH firstlink and secondLink no matter who i add to the database and i have no idea why its doing it!
The datatype for both rows is INT(15)
Remove intval and all will work fine.
$firstlink = mt_rand(100, 999) . mt_rand(100, 999) . mt_rand(1, 9) . mt_rand(100, 999); // 10 digit
32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. With intval you got 2147483647 mostly.
You can simplify your code and improve the randomness of the code like this:
$firstlink = mt_rand(10000,99999) . mt_rand(10000,99999);
$secondLink = mt_rand(10000,99999) . mt_rand(10000,99999);
echo "INSERT INTO userAccount
(Category,Fname,LName,firstlink,secondLink,AccDate)
VALUES ( '" . $cat . "',
'" . $fname . "',
'" . $lname . "',
" . $firstlink . ",
" . $secondLink . ",
'" . date('Y-m-d g:i:s',time()). "');"
PHPFiddle: http://phpfiddle.org/main/code/6nf-wpk
This will build your random 10-digit code by making two random 5 digit codes and joining them together. Is is simpler and easier to follow with less parts making it up. It had to be done with two mt_rand()s because the maximum number possible is 2147483647. For each mt_rand() function you're using, you're preventing a 0 from being the first digit in that section of the number, because you're starting the first digit at between 1 and 9.
If you don't care about the first number being only a 1 or 2 (and never being 3-9 or 0) you can simply use
$firstlink = mt_rand(1000000000,2147483647); // random 10 digit number
$secondLink = mt_rand(1000000000,2147483647); // random 10 digit number
As general coding tips:
Be consistent with how you name variables. You have a lowercase "L" in "$firstlink" and a capital "L" in "$secondLink". PHP is case-sensitive and you'll end up using the wrong name and getting unexpected (blank) results elsewhere in your program.
Be be careful never to put any user-provided data into a SQL command without protecting against SQL Injection attacks. Use parameterized queries as a rule. See How can I prevent SQL injection in PHP? for more details and examples.

Formatting a mysql number from a select statement into php

I am using mysql 5.1 database and have a # of fields in them that look like this for format:
1234567
When I output them to via php, I would like them formatted like this:
1,234,567
There are no decimals involved.
The select statement is pulling 30 records from my database. Each record has (2) fields that I need formatted thus. Weight and Cost as well as 16 other fields that I need, but do not need formatting. They are being read and entered int a table.
Suggestions?
Note:
Data Fields: Cost Weight
Table: Warships
Current Select statement:
$result = mysql_query('SELECT * FROM `Warships` WHERE `Type` = "BC" ');
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['SHIP CLASS'] . "</td>";
echo "<td>" . $row['CAT'] . "</td>";
echo "<td>" . $row['Type'] . "</td>";
echo "<td>" . $row['WEIGHT'] . "</td>";
echo "<td>" . $row['Cost'] . "</td>";
I think PHP's number_format is what you need.
$num = number_format(1234567);
echo $num; // 1,234,567
If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands. More info from PHP API
You're looking for the number_format function. Pass your number to it as the first parameter and it will add in a comma for the thousands separator.
Example:
echo "<td>" . number_format($row['Cost']) . "</td>";
number format
$num_format = number_format(1234567);
echo $num_format ; // 1,234,567

Categories