issue with php number_format() - php

I'm having an issue with number_format. When $val is over 1,000 in value, the $update will only SET a value of 1. If it is less than 1,00 in value, it will SET the correct value.
pmV is DECIMAL, 7,2.
I'm sure that I have just stared at this for too long and am missing something. What am I doing wrong? Please school me! ;)
// Set variables for received data
$id = strval($_GET['id']); // value is 1
$k = strval($_GET['k']); // value is 1
$dwt = strval($_GET['dwt']); // value is 25
$spot = "." . strval($_GET['spot']); // value is .70
//Query the database based on the variables received and 'echo' the results back
$sql="SELECT * FROM metals WHERE id = '".$id."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
if ($id == 1){ // If we are calculating Gold, then add Karat into the calculation
$num = ((($row['value']/20)*$k)*$dwt)*$spot; //$row['value']=1200.01
}
else { // If not, then don't
$num = (($row['value']/20)*$dwt)*$spot;
}
$val = number_format($num,2,'.',',');
echo $val; // Send the value back to page --> Sending correct value - 1,050.01
// Update the DB with the calculated PM amount
$update="UPDATE totals SET pmV = $val WHERE id='1'";
$result2 = mysqli_query($con,$update); // UPDATES value of pmV to '1' instead of 1,050.01
// Get the Diamond Value from the DB and Update the Total calculation
$select="SELECT dV FROM totals WHERE id='1'";
$result3 = mysqli_query($con,$select);
while($dv = mysqli_fetch_array($result3)) {
$val2 = $dv['dV']+$val;
$sql4 = "UPDATE totals SET total = $val2 WHERE id='1'";
$result4 = mysqli_query($con,$sql4);
};
};
mysqli_close($con);

1,050.01 is not a valid number. It's a formatted string. So when you try to treat it like a number, things break.
To round a number to teo decimal places, try this:
$val = floor($num*100)/100;

Related

How to assign value to an array in while loop in php from mysqli result to make a counter to filter another while loop?

How to assign value to an array in while loop in php from mysqli result to make a counter to filter another while loop??
I want to assign something like this for my counter variable:
$counter = array("6:00 Am" => 0, "8:00 Am" => 0, "10:00 Am" => 0);
For this code:
//This is from transaction table
$stm2 = "SELECT tr_sched FROM transaction WHERE tr_date = CURRENT_DATE()";
$res2 = $conn->query($res2);
while($rows5 = $res2->fetch_assoc())
{
//Not working
$counter[] = array($rows5['tr_sched'] => 0)
}
So I can filter this another while loop if the schedule time is greater than to my limit variable, like this:
//This is from my schedule table
$stm = "SELECT sc_time FROM schedule GROUP BY sc_time";
$res = $conn->query($stm);
$counter = array();
while($row4 = $res4->fetch_assoc())
{
//Note working
if($counter[$row4['sc_time']] >= $limit/*=10*/)
{
echo "<option disabled="">" . $row4['sc_time'] . "</option>";
}
else
{
echo "<option>" . $row4['sc_time'] . "</option>";
}
}
The goal of all the codes above is to display all schedule time from schedule table as an option for select element and if the schedule time is already have a 10 records or greater than(limit variable) on my transaction table for today it will display as option but disable so it can't be selected by user.
I hope you get what I mean, I will try to keep active to answer if you have something to clarify about my question.
You don't need the while loop at all.
You can use array functions to populate the array with static values.
$stm2 = "SELECT tr_sched FROM transaction WHERE tr_date = CURRENT_DATE()";
$res2 = $conn->query($stm2);
// get values from a single column
$keys = array_column($res2->fetch_all(MYSQLI_ASSOC), 'tr_sched');
// create an array with all values as 0 and keys from $keys
$counter = array_fill_keys($keys, 0);
Of course, don't reset the array later on with $counter = array();
If you want to loop anyway, then you can use a simple foreach loop.
$stm2 = "SELECT tr_sched FROM transaction WHERE tr_date = CURRENT_DATE()";
$res2 = $conn->query($stm2);
foreach($res2 as $rows5) {
$counter[$rows5['tr_sched']] = 0;
}

pHp Issue: "Waiting for localhost": Maybe infinite loop issue?

I am currently working on an elo based matchmaking system. Basically, I have a database where there are a bunch of users, each having their respective ratings.
Brief explanation of code, it chooses one user at random, and chooses another user if the second user is within +-100 difference-elo of the first user (so grandmasters don't play with bronze players). If there is no one within 100 elo, the difference-elo increments by 50 and checks again.
Problem: I created a test user that is 100 elo more than the other users to test the matchmaking system. The program works except for when the first selected player is my test user. The page never loads and it is stuck on "Waiting for localhost". I assumed this meant one of my while loops was going on infinitely, but after spending sometime editing them and trying to figure out why they might be going on infinitely, the error still persists.
<?php
include('mysql.php');
include('functions.php');
$result2 = executeQuery("SELECT * FROM images ORDER BY score DESC");
function executeQuery($query2){
$connect = mysqli_connect("localhost", "root", "password","database");
$result2 = mysqli_query($connect, $query2);
return $result2;
}
// Get random
$query="SELECT * FROM images ORDER BY RAND() LIMIT 0,1";
$result = #mysqli_query($connection, $query);
//Put random in images array
while($row = mysqli_fetch_object($result)) {
$images[] = (object) $row;
}
//Get elo of random
$elo1 = $images[0]->score;
--------------------------
//Point of Interest Below
--------------------------
//Sort database by DESC. Then go through entire database. If current row's elo is with +- difference (which right now is 100) of elo1's rating, ($elo1-100 < x < $elo1+100), then put into new array with all matchups.
//Get length of array, if length is 0 (meaning no match ups were found), increase difference by 50 and try again.
$potentialMatchup = [];
$diff = 100;
$arrayLength = count($potentialMatchup);
while ($arrayLength == 0){
$diff += 50;
while($row2 = mysqli_fetch_object($result2)){
if(($row2->score > $elo1-$diff) && ($row2->score < $elo1+$diff)){
$potentialMatchup[] = (object) $row2;
}
}
$arrayLength = count($potentialMatchup);
}
-------------------------------
//Get random index between 0 and length of array.
$randomNumber = rand(0, $arrayLength-1);
//Put match up into images array
$images[1] = (object) $potentialMatchup[$randomNumber];
//Get names of images
$nameLeft = $images[0]->filename;
$nameRight = $images[1]->filename;
//If same person, pick another random
while($nameLeft == $nameRight){
$randomNumber = rand(0, $arrayLength-1);
$images[1] = (object) $potentialMatchup[$randomNumber];
$nameRight = $images[1]->filename;
}
// Close the connection
mysqli_close($connection);
$leftName = str_replace("_", " ", $images[0]->filename);
$rightName = str_replace("_", " ", $images[1]->filename);
?>

Between min and max value mysqli

I have to create a PHP web page with two text fields in which the user can enter minimum and maximum item prices from a SQL database. So I have items with prices. For example, if a user wants to see items between the prices 4 and 15, he can submit it and then it will show only the items in that price range. How can I do this? How to echo this?
Thank you!
I have this so far:
$min=$_POST["minimum"];
$max=&$_POST["maximum"];
$result = mysqli_query($con,"SELECT * FROM items WHERE selling price BETWEEN {$min}+1 AND {$max}");
Apart from a major SQL Injection issue, your script is looking fine. Just some small typs and syntax errors. Compare this one to yours:
$min=(int)$_POST["minimum"];
$max=(int)$_POST["maximum"];
$result = mysqli_query($con,"SELECT * FROM items WHERE selling_price BETWEEN {$min}+1 AND {$max}");
So, what did I change?
At least cast posted values to int to remove the chance of anyone injecting malicious SQL code into your query. You should use proper escaping in the future
You dont need to add the & character before in line two. You dont need to assign the value by reference. just assign the plain old way
column and table names can not conain spaces in MySQL. Are you sure that is the correct name of the column? Maybe there was an underscore?
One of the many safer and simpler ways of doing that would be
$dsn = "mysql:dbname=test;host=127.0.0.1";
$dbh = new PDO($dsn, 'username', 'password');
if(isset($_POST["minimum"]) && isset($_POST["maximum"]))
{
$min=floatval($_POST["minimum"]); //+1 is not needed
$max=floatval($_POST["maximum"]);
$sth = $dbh->prepare("SELECT * FROM items WHERE selling_price BETWEEN ? AND ?");
$sth->execute(array($min,$max));
while($row = $sth->fetch(PDO::FETCH_OBJ))
{
print_r($row);
}
}
That should do the trick for you:
if(isset($_POST['minimum'])){
$min = $_POST['minimum'];
}else{
$min = '';
}
if(isset($_POST['maximum'])){
$max = $_POST['maximum'];
}else{
$max = '';
}
$sql = "SELECT * FROM item WHERE selling_brice > '$min' AND selling_price < '$max'";
$query = mysqli_query($con, $sql);
$count = mysqli_num_rows($query);
if($query == true && $count > 0 ){
while ($row = mysqli_fetch_assoc($query)){
$price .= $row['selling_price'];
$price .= '<br />'
}
echo $price;
}else{
echo "NO results to Display";
}
Ofcourse this is not the best programing mysql injections, your query uses * etc....but this should work.

Auto Insert into MySql Data Base

When one User Enter all his/her details after enter he will get a message like his registration no /ID is Like:
A0001
2nd is
A0002
like this upto A1000
after this the registration no automaticaly change to B0001
Is It Possible!!!!!
for ($i = 'A'; $i != 'AA'; $i++)
{
$prefix = $i;
$id = $prefix.sprintf("%03s",$suffix);
for ($j=1;$j<=5;$j++)
{
$res = "$id"."$j";
echo "$res"."<br>";
}
}
this is the code only to A005 to Z005 but how can i able to pick A001 and insert into mysql database first column.
This is quite simple:
1st what you want to do is to query the database for the previous registration no /ID.
something like this:
$query = mysqli_query($connect,'SELECT regCode From data ORDER BY regCode DESC LIMIT 1');
then you check if there is any result like this:
$results = count(mysqli_num_rows($query));
if it $results returns 0 (it is a fresh database) do this:
$regCode = 'A0001';
else:
create an array of alphabets.
$alphabet = ['B','C','D','E']; #from B to Z (A is omitted because it is the default prefix)
retrieve previous regCode like this:
list($regCode) = mysqli_fetch_row($query);
From here seperate the alphabet from the numbers
$prefix = substr($regCode,0,1); //get prefix/alphabet
$storage_id = (int) substr($regCode,1,4) +1; //get code and add 1
Now test for the limit which in our case is 1000 (or any number you want):
$limit = 1000
if($storage_id>$limit){
$storage_id= '0001'; //if limit exceeded reset storage id
$index = array_search($prefix,$alphabet); //get alphabet/prefix index in the $alphabet array
if($index>=0){
$prefix = $alphabet[$index+1]; //Get next alphabet
}
}else{
//when limit is not exceeded do this
if(strlen($store)!=4){ //check the length of our regCode (should be 4 letters in this case if not add some zeros)
$storage_id = str_pad($storage_id,4,'0',STR_PAD_LEFT);
}
}
$regCode = $prefix.$store; //combine alphabet to new storage_id
echo $regCode;
And that's it !!!
This is the full code. Just copy this:
<?php
mysql_connect('localhost','root','');
mysql_select_db('test');
if(isset($_REQUEST['submit']))
{
$query = mysql_query('SELECT regno from details ORDER BY regno DESC LIMIT 1');
$results = mysql_num_rows($query);
if($results==0){
$regCode = 'A0001';
mysql_query("INSERT INTO details (regno) VALUES('{$regCode}')");
}else{
list($regCode) = mysql_fetch_row($query);
$alphabet = array('B','C','D','E');
$prefix = substr($regCode,0,1); //get prefix/alphabet
$storage_id = (int) substr($regCode,1,4) +1;
$limit = 1000;
if($storage_id>$limit){
$storage_id= '0001'; //if limit exceeded reset storage id
$index = array_search($prefix,$alphabet); //get alphabet/prefix index in the $alphabet array
if($index>=0){
$prefix = $alphabet[$index+1]; //Get next alphabet
}
}else{
//when limit is not exceeded do this
if(strlen($storage_id)!=4){ //check the length of our regCode (should be 4 letters in this case if not add some zeros)
$storage_id = str_pad($storage_id,4,'0',STR_PAD_LEFT);
}
}
$regCode = $prefix.$storage_id; //combine alphabet to new storage_id
mysql_query("INSERT INTO details (regno) VALUES('{$regCode}')");
}
echo $regCode;
}
?>
<form name="form" id="form" method="post">
<input type="submit" name="submit">
</form>

How generate UNIQUE random number in php [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Algorithm for generating a random number
Hi i need to assign a randomly generated number to some entries into the database and it must be unique.
I use:
$random_number = mt_rand();
mysqli_query($db_connection, "INSERT INTO my_table (rand_num, blabla) VALUES ('$random_number', '$blabla')");
But ofc there could always be a slightly low chance that 2 random numbers will be the same.
Then i could do something like:
function random_check($random_number) {
require_once('db_access.php');
$random_check = mysqli_query($db_connection, "SELECT rand_num FROM my_table");
mysqli_close($db_connection);
$result = 1;
while($row = mysqli_fetch_array($random_check)){
if ($row['rand_num'] == $random_number) {
$result=0
}
}
return $result;
};
$random_number = mt_rand();
$random_check = random_check($random_number);
if ($random_check == 0) {
$random_number = mt_rand();
}
But this would only check the number once and there will still be a chance that the new generated number already exists into the db.
Any suggestions?
Thanks
Here is a method which you can use:
<?php
$num= mt_rand();
$con = mysql_connect("localhost","uname","password");
mysql_select_db("dbname",$con);
$sel_query = "SELECT * FROM my_table WHERE rand_num =%d"; // query to select value
$ins_query = "INSERT INTO my_table(rand_num) VALUES(%d)"; // query to insert value
$result = mysql_query(sprintf($sel_query,$num),$con);
while( mysql_num_rows($result) != 0 ) { // loops till an unique value is found
$num = mt_rand();
$result = mysql_query(sprintf($sel_query,$num),$con);
}
mysql_query(sprintf($ins_query,$num),$con); // inserts value
?>
Doing a SELECT rand_num FROM my_table and checking the resulting values is very, very inefficient. Use a WHERE clause:
do {
$random_number = mt_rand();
$query_object = mysqli_query($db_connection, "SELECT 1 FROM my_table WHERE rand_num = $random_number");
$query_record = mysqli_fetch_array($query_object);
if(! $query_record) {
break;
}
} while(1);
It is possible to write this code in lesser lines.
function random_check($random_number) {
require_once('db_access.php');
$random_check = mysqli_query($db_connection, "SELECT rand_num FROM my_table");
mysqli_close($db_connection);
while($row = mysqli_fetch_array($random_check)){
if ($row['rand_num'] == $random_number) {
return false;
}
}
return true;
};
while(!random_check(mt_rand()){
$myNumbber = random_check(mt_rand();
}
--> Now u got unique number in "myNumber"
md5( strtotime("now").$_SERVER['REMOTE_ADDR'] );
strtotime("now") would give you a unique number, but ifyou are using this script to process forms/uploads etc from multiple users, the ip address will just make certain of that (on the off chance that at the exact same second two entries are made... can that even happen?? hmm...)
md5() cos i felt like it :D

Categories