John Davidson

php - Using loops by reading data from a database

0 comments
Message:


I have a form with three fields that I want to read separately from the database


 $_POST['wkNumer1'];
$_POST['wkNumer2'];
$_POST['wkNumer3'];

How can I read this data without repeating the same code 3 times? In this code, only the variable $wkNumer value will be change.


<?php
if (isset($_POST['show_diagram'])) {

$goodname = $_POST['htDriver'];
$wkNumer = $_POST['wkNumer1'];

// Table with data
$sql = "SELECT WorkingDay, OrderNo, NameFinish, Type FROM `status` where WEEK(WorkingDay) = :wknumer AND NameFinish = :nameFinish"; // SQL with parameters
$stmt = $conn->prepare($sql);
$stmt->bindParam("wknumer", $wkNumer);
$stmt->bindParam("nameFinish", $goodname);
$stmt->execute();
$OCSdatas = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();

$countWithoutE = 0;
$countE = 0;
foreach ($OCSdatas as $data) {

if ($data['Type'] != 'E') {
$countWithoutE = $countWithoutE + 1 ;
}

if ($data['Type'] == 'E') {
$countE = $countE + 1 ;
}
}
echo $goodname . '<br />';
echo $wkNumer . '<br />';
echo $countWithoutE . '<br>';
echo $countE . '<br>';
$countE = $countE/2;
$countTotal = $countWithoutE + $countE;
echo $countTotal/5 . '<br>';
echo $count/5;
}


?>


My Answer:
You can achieve this by using a loop to iterate over an array of field names and then accessing the corresponding values from the $_POST array. Here's an example code snippet:

php
// Define an array of field names
$fieldNames = ['wkNumer1', 'wkNumer2', 'wkNumer3'];

// Loop through the field names array
foreach ($fieldNames as $fieldName) {
// Check if the field exists in the $_POST array
if (isset($_POST[$fieldName])) {
// Get the value of the field
$wkNumer = $_POST[$fieldName];

// Do something with the $wkNumer value
echo $wkNumer . "
";
}
}


In this code snippet, we define an array of field names and then loop through each field name. We check if the field exists in the $_POST array and if it does, we retrieve the value and perform any necessary operations on it. This way, you can avoid repeating the same code 3 times for each field.

Rate this post

3 of 5 based on 2668 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us