Вставка сохраняет только первую цифру, остальные игнорируются

0

У меня есть вопрос относительно моей базы данных. Я разработал систему, в которой он будет автоматически вычислять процент, когда пользователь вставляет значения. Моя проблема сейчас, моя база данных только сохранила первую цифру. Например, если я вхожу в 4000, он будет хранить только 4, и сначала я подумал, что, возможно, что-то происходит с тремя нулями позади, но это не так, и если я вставляю 3245, он все равно сохраняет только 3.

Ниже приведена моя база данных; Изображение 174551

и здесь коды, связанные с этой базой данных.

добавить записи:

<form action="" method="post">

<div>

<?php if ($id != '') { ?>

<input type="hidden" name="id" value="<?php echo $id; ?>" />

<p>ID: <?php echo $id; ?></p>

<?php } ?>





<p><strong>Tarikh&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: *</strong>

<input type="text"  style="text-transform:uppercase" name="date" value=" <?php echo $date; ?>"/><br/></p>

<p><strong>Di bawah 60 Minit  : *</strong> <input type="text" name="casesolved_u"

value="<?php echo $casesolved_u; ?>"/><br/></p>

<p><strong>Jumlah kes &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: *</strong> <input type="text" name="casesolved_a"

value="<?php echo $casesolved_a; ?>"/></p>



<!--Remove Percentage entry -->


<p>* required</p>

<input type="submit" name="submit" value="Submit" />

</div>

</form></center>



</body>

</html>



<?php }



/*

EDIT RECORD

*/

// if the 'id' variable is set in the URL, we know that we need to edit a record

if (isset($_GET['id']))

{

// if the form submit button is clicked, we need to process the form

if (isset($_POST['submit']))

{

// make sure the 'id' in the URL is valid

if (is_numeric($_POST['id']))

{

// get variables from the URL/form

$id = $_POST['id'];

$date = strtoupper($_POST['date']);

$casesolved_u = htmlentities($_POST['casesolved_u'], ENT_QUOTES);

$casesolved_a = htmlentities($_POST['casesolved_a'], ENT_QUOTES);



//check if empty

if ($date == '' || $casesolved_u == ''||$casesolved_a =='')

{

// if they are empty, show an error message and display the form

$error = 'ERROR: Please fill in all required fields!';

renderForm($date, $casesolved_u, $casesolved_a, $percentage ,$error, $id);

}

else

{

	$percentage = ($casesolved_u * 100 / $casesolved_a);

	//apply the proper formatting

$casesolved_u = number_format ($casesolved_u, 2);
$casesolved_a = number_format ($casesolved_a, 2);
$percentage = number_format ($percentage,2);
 


// if everything is fine, update the record in the database

if ($stmt = $mysqli->prepare("UPDATE ae SET date = ?, casesolved_u = ?, casesolved_a=?, percentage=?

WHERE id=?"))

{

$stmt->bind_param("ssssi", $date, $casesolved_u, $casesolved_a, $percentage ,$id);

$stmt->execute();

$stmt->close();

}

// show an error message if the query has an error

else

{

echo "ERROR: could not prepare SQL statement.";

}



// redirect the user once the form is updated

header("Location: view.php");

}

}

// if the 'id' variable is not valid, show an error message

else

{

echo "Error!";

}

}

// if the form hasn't been submitted yet, get the info from the database and show the form

else

{

// make sure the 'id' value is valid

if (is_numeric($_GET['id']) && $_GET['id'] > 0)

{

// get 'id' from URL

$id = $_GET['id'];



// get the recod from the database

if($stmt = $mysqli->prepare("SELECT id, date, casesolved_u, casesolved_a, percentage FROM ae WHERE id =?"))



{

$stmt->bind_param("i", $id);

$stmt->execute();



$stmt->bind_result($id, $date, $casesolved_u, $casesolved_a, $percentage);

$stmt->fetch();



// show the form

renderForm($date, $casesolved_u, $casesolved_a , $percentage, NULL, $id);



$stmt->close();

}

// show an error if the query has an error

else

{

echo "Error: could not prepare SQL statement"; 

}

}

// if the 'id' value is not valid, redirect the user back to the view.php page

else

{

header("Location: view.php");

}

}

}




/*

NEW RECORD

*/

// if the 'id' variable is not set in the URL, we must be creating a new record

else

{

// if the form submit button is clicked, we need to process the form

if (isset($_POST['submit']))

{

// get the form data

$date = strtoupper($_POST['date']);

$casesolved_u = htmlentities($_POST['casesolved_u'], ENT_QUOTES);

$casesolved_a = htmlentities($_POST['casesolved_a'], ENT_QUOTES);



// check that no empty value inserted

if ($date == '' || $casesolved_u == '' ||$casesolved_a == '')

{

// if they are empty, show an error message and display the form

$error = 'ERROR: Please fill in all required fields!';

renderForm($date, $casesolved_u, $casesolved_a, $percentage, $error);

}

else

{


	$percentage = ($casesolved_u * 100 / $casesolved_a);

	//apply the proper formatting

$casesolved_u = number_format ($casesolved_u, 2);
$casesolved_a = number_format ($casesolved_a, 2);
$percentage = number_format ($percentage,2);


// insert the new record into the database

if ($stmt= $mysqli->prepare ("INSERT INTO ae (date, casesolved_u, casesolved_a, percentage) VALUES (?,?,?,?)"))

{

$stmt->bind_param("ssss",$date, $casesolved_u, $casesolved_a, $percentage);

$stmt->execute();

$stmt->close();

}

// show an error if the query has an error

else

{
echo "ERROR: Could not prepare SQL statement.";

}

// redirec the user

header("Location: view.php");

}

}

// if the form hasn't been submitted yet, show the form

else

{

renderForm();

}

}

// close the mysqli connection

$mysqli->close();

?>

и вот код представления;

<?php
// connect to the database
include('connect-db.php');

// get the records from the database
if ($result = $mysqli->query("SELECT * FROM ae ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";

// set table headers
echo "<tr><th>&nbsp Tarikh &nbsp</th><th> &nbsp Discaj Dalam Masa 2 Jam &nbsp </th><th> &nbsp Jumlah Kes &nbsp </th><th>Peratusan</th><th>&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp</th><th>&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp</th></tr>";

while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";

echo "<td>" . $row->date . "</td>";
echo "<td>" . $row->casesolved_u . "</td>";
echo "<td>" . $row->casesolved_a . "</td>";
echo "<td>" . $row->percentage . "</td>";
echo "<td><a href='records.php?id=" . $row->id . "'>Edit</a></td>";
echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>";
echo "</tr>";
}

echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "Tiada maklumat untuk dipamerkan";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}

// close database connection
$mysqli->close();

?>
<p>
</p>
 <center><a href="records.php">  Tambah Rekod Baru</a></center>
</div>

Пожалуйста, укажите мне, где я делаю неправильные действия, которые заставляют мою базу данных хранить только первую цифру в базе данных.

Теги:
phpmyadmin

1 ответ

2
Лучший ответ

number_format помещает запятые в качестве разделителей тысяч. Это собирается испортить любую вставку в MySQL (или большинство других баз данных), если число составляет> 1,000 - например, 4000 или 3,245. number_format необходим для того, чтобы люди могли легко читать информацию, но не для базы данных.

  • 0
    Итак, что я должен сделать, чтобы это исправить?
  • 0
    @WanHazyan - Начните с замены всех вызовов функции number_format ($ x, 2) на round ($ x, 2)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню