Only 1 row is inserted in foreach - php

UPDATE:
I have managed to correct some things. But only the first row is inserted. If the first row is not selected, nothing gets inserted.
I want only selected checkboxes from the populated table inserted into the a new table.
My table is as follows:
<table id="simple-table" class="table table-striped table-condensed responsive">
<thead>
<tr>
<th style="width:5%" class="center">
<label class="pos-rel">
<input type="checkbox" name="checked" class="ace" />
<span class="lbl"></span>
</label>
</th>
<th style="width:32%">Student Name</th>
<th style="width:13%">Adm. No</th>
<th style="width:10%" class="center">CA1 (10%)</th>
<th style="width:10%" class="center">CA2 (10%)</th>
<th style="width:10%" class="center">CA3 (10%)</th>
<th style="width:10%" class="center">Exam (70%)</th>
<th style="width:10%" class="center">Total (100%)</th>
</tr>
</thead>
<tbody>
<?php
if(isset($_POST['loadStudents'])){
$session = clean($_POST["session"]);
$term = clean($_POST["term"]);
$c_taught = clean($_POST["c_taught"]);
$s_taught = clean($_POST["s_taught"]);
$process_limit = clean($_POST["process_limit"]);
$session_phrase = "Session";
$sql = "SELECT `id`, `StudentID`, `StudentName` FROM tbl_students WHERE `StudentClass` = '".$c_taught."' ORDER BY `StudentName` ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$cnt=1;
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$student_name = $row['StudentName'];
$student_id = $row['StudentID'];
?>
<tr>
<td class="center">
<label class="pos-rel">
<input type="checkbox" class="ace" name="checked[]" value="<?php echo $row['id'];?>" />
<span class="lbl"></span>
</label>
</td>
<td><?php echo $student_name; ?><input type="hidden" name="student_name[]" value="<?php echo $row['StudentName']; ?>"/></td>
<td><?php echo $student_id; ?><input type="hidden" name="student_id[]" value="<?php echo $row['StudentID']; ?>"/></td>
<td class="center"><?php echo '<input type="text" maxlength="2" size="6" name="CA1[]" autofocus>'; ?></td>
<td class="center"><?php echo '<input type="text" maxlength="2" size="6" name="CA2[]">'; ?></td>
<td class="center"><?php echo '<input type="text" maxlength="2" size="6" name="CA3[]">'; ?></td>
<td class="center"><?php echo '<input type="text" maxlength="2" size="6" name="Exam[]">'; ?></td>
<td class="center"><?php echo '<input type="text" maxlength="2" size="6" name="Total[]">'; ?></td>
</tr>
<?php $cnt=$cnt+1;}}
else {
$msg = "<span class='red'><h4> No data available for your selection. </h4></span>";
}
}
?>
</tbody>
</table>
My inset script is as follows: (On the same page with the form)
<?php
$enroll_sql = "";
if(isset($_POST['add_assessment'])) {
if(empty($_POST['checked'])){
echo '<script>alertify.alert("No Student is selected.",function(e){if(e){document.location.href = "cass_entry.php";}}).set("labels", {ok:"OK!"}).set("defaultFocus", "ok").set("title", "Assessment")
</script>';
exit();
}
foreach($_POST['checked'] as $id=>$value) {
$session = $_POST['session'];
$term = $_POST['term'];
$c_taught = $_POST['c_taught'];
$s_taught = $_POST['s_taught'];
$student_id = $_POST['student_id'][$id];
$student_name = $_POST['student_name'][$id];
$ca_1 = $_POST['CA1'][$id];
$ca_2 = $_POST['CA2'][$id];
$ca_3 = $_POST['CA3'][$id];
$exam = $_POST['Exam'][$id];
$total = $_POST['Total'][$id];
$enroll_sql .= '
INSERT INTO tbl_subjects_enrollment (`Session`,`Term`,`Student_Class`,`Subject_Name`,`Student_ID`,`Student_Name`,`CA_1`,`CA_2`,`CA_3`,`Exam`,`Total`)
VALUES("'.$session.'", "'.$term.'", "'.$c_taught.'", "'.$s_taught.'", "'.$student_id.'", "'.$student_name.'", "'.$ca_1.'", "'.$ca_2.'", "'.$ca_3.'", "'.$exam.'", "'.$total.'")';
echo $enroll_sql;
if (mysqli_multi_query($conn, $enroll_sql)) {
$success_msg = '<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">
<i class="ace-icon fa fa-times"></i>
</button>
<h4><i class="ace-icon fa fa-check"> Success</i></h4>
<p>Assessment scores were successfully saved.</p></div>';
} else {
echo "Error saving Assessment: " . $conn->error;
}
}
}
?>

Watch, your first checkbox isn't named as an array and has no value :
<input type="checkbox" name="checked" class="ace" />
It may result in a simple var $_POST['checked'] which isn't an array (nor a string since it hasn't value) and won't be passed in your foreach.

Look :
foreach($_POST['checked'] as $id=>$value) {
$enroll_sql .= '
INSERT INTO tbl_subjects_enrollment (`Session`,`Term`,`Student_Class`,`Subject_Name`,`Student_ID`,`Student_Name`,`CA_1`,`CA_2`,`CA_3`,`Exam`,`Total`)
VALUES("'.$session.'", "'.$term.'", "'.$c_taught.'", "'.$s_taught.'", "'.$student_id.'", "'.$student_name.'", "'.$ca_1.'", "'.$ca_2.'", "'.$ca_3.'", "'.$exam.'", "'.$total.'")';
echo $enroll_sql;
if (mysqli_multi_query($conn, $enroll_sql)) {
$success_msg = '<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">
<i class="ace-icon fa fa-times"></i>
</button>
<h4><i class="ace-icon fa fa-check"> Success</i></h4>
<p>Assessment scores were successfully saved.</p></div>';
} else {
echo "Error saving Assessment: " . $conn->error;
}
}
You concatenate your SQL query each time => and execute it each time adding the previous queries.
If you didn't forget your semi-colon it would have ended inserting too many time the same line (and actually that's why only the first Insert is working).
The problem here is the concatenation of the query AND the missing semi-colon of your query.
In order to make your code work fine, you juste have to not concatenate your query :
$enroll_sql = '...'; // = not .=
OR
let it concatenated BUT execute the query OUTSIDE your foreach loop (and adding a semi-colon at the end of the SQL query :
, "'.$total.'");'; // ; at the end of the query

I wanna thank all contributors especially #WizardNx.
I eventually solved it (Necessity is the mother of creativity):
It appears the checkbox was not assigning unique id to each row. In fact, if I check row_3 and fill all the inputs, it will insert for row_1 but assign row_3 id.
Here is what I did:
<tr>
<td class="center">
<label class="pos-rel">
<input type="checkbox" class="ace" name="studentSelect[<?php echo $row['id']; ?>]" value="<?php echo $row['StudentID']; ?>" />
<span class="lbl"></span>
</label>
</td>
<td><?php echo $row['StudentName']; ?><input type="hidden" name="student_name[<?php echo $row['id']; ?>]" value="<?php echo $row['StudentName']; ?>"/></td>
<td><?php echo $row['StudentID']; ?></td>
<td class="center"><input type="text" maxlength="2" size="6" name="CA1[<?php echo $row['id']; ?>]" autofocus></td>
<td class="center"><input type="text" maxlength="2" size="6" name="CA2[<?php echo $row['id']; ?>]"></td>
<td class="center"><input type="text" maxlength="2" size="6" name="CA3[<?php echo $row['id']; ?>]"></td>
<td class="center"><input type="text" maxlength="2" size="6" name="Exam[<?php echo $row['id']; ?>]"></td>
<td class="center"><input type="text" maxlength="2" size="6" name="Total[<?php echo $row['id']; ?>]"></td>
</tr>
I added id to each input on each row.

Related

how to make inline update?

I have a table of products (data pulled from SQL database) with this fields: ID, Name, Price.
After i pulled the data i have a QTY cell for each product...
I want to make a cell at the bottom to sum all the qty*prodcut price to get total price of the order...
That's my table:
<table>
<tr>
<td>Name</td>
<td>Price</td>
<td>Qty</td>
</tr>
<form action="sendorder.php?supid=<?php echo $supid; ?>" method="post">
<?php
while($row = mysqli_fetch_array($result)) {
$prodname = $row['name'];
$supid = $row['supplier'];
$prodid = $row['id'];
$prodprice = $row['price'];
?>
<tr>
<td>
<input type="checkbox" name="prod[]" id="prod[<?php echo $prodid; ?>]" value="<?php echo $prodid; ?>">
<label for="prod[<?php echo $prodid; ?>]"><?php echo $prodname; ?></label>
</td>
<td>
<?php echo number_format($prodprice, 2); ?><label for="prod[<?php echo $prodid; ?>]"> NIS</label>
</td>
<td>
<label for="prod[<?php echo $prodid; ?>]"><input style="font-size: 12px;" type="text" name="qty_<?php echo $prodid; ?>" placeholder="Qty" minlength="1" maxlength="3" size="2"></label>
</td>
</tr>
<?php
}
?>
<tr>
<td><b>Total Price:</b></td>
<td rowspan="1" colspan="2">XXX NIS</td> \\ HERE I WANT TO MAKE THE LIVE CALCLUTION
</tr>
<tr>
<td rowspan="1" colspan="3">
<input type="submit" name="submit" value="Submit">
</td>
</tr>
</form>
tnx for everyone, i found this LINK
and that's excatly what i was looking for.
function getTotal(){
var total = 0;
$('.sum').each(function(){
total += parseFloat(this.innerHTML)
});
$('#total').text(total);
}
getTotal();
$('.qty').keyup(function(){
var parent = $(this).parents('tr');
var price = $('.price', parent);
var sum = $('.sum', parent);
var value = parseInt(this.value) * parseFloat(price.get(0).innerHTML||0);
sum.text(value);
getTotal();
})
add $sum = 0; variable before while and put $sum += $row['price']; inside your while you can access $sum in Total Price <td>.
maybe you need int cast for $row['price'].
<table>
<tr>
<td>Name</td>
<td>Price</td>
<td>Qty</td>
</tr>
<form action="sendorder.php?supid=<?php echo $supid; ?>" method="post">
<?php
$sum = 0;
while($row = mysqli_fetch_array($result)) {
$prodname = $row['name'];
$supid = $row['supplier'];
$prodid = $row['id'];
$prodprice = $row['price'];
$sum += $row['price'];
?>
<tr>
<td>
<input type="checkbox" name="prod[]" id="prod[<?php echo $prodid; ?>]" value="<?php echo $prodid; ?>">
<label for="prod[<?php echo $prodid; ?>]"><?php echo $prodname; ?></label>
</td>
<td>
<?php echo number_format($prodprice, 2); ?><label for="prod[<?php echo $prodid; ?>]"> NIS</label>
</td>
<td>
<label for="prod[<?php echo $prodid; ?>]"><input style="font-size: 12px;" type="text" name="qty_<?php echo $prodid; ?>" placeholder="Qty" minlength="1" maxlength="3" size="2"></label>
</td>
</tr>
<tr>
<td><b>Total Price:</b></td>
<td rowspan="1" colspan="2"><?php echo $sum; ?></td> \\ HERE I WANT TO MAKE THE LIVE CALCLUTION
</tr>
<?php
}
?>
<tr>
<td rowspan="1" colspan="3">
<input type="submit" name="submit" value="Submit">
</td>
</tr>
</form>

Update shopping cart quantity PHP

I'm building a test shopping site using PHP / mySQL
here is my code:
the show_product.php:
<form method ="get" action="addtocart.php">
<input type="hidden" name="id_product" value='.$row['id_product'].'>
<tr>
<th colspan="2">'.$row['name'].'</th>
</tr>
<td>
<img align="center" src='.$row['photo'].' alt="">
</td>
<td>'.mb_substr($row['description'],0,200).'....</td>
<tr></tr>
<td>
'.$row['price'].'€<input type="number" name="quantity" value="1" min="1" max="20">
</td>
<td> <button type="submit" class="btn">add to cart</button></form>
the addtocart.php
session_start()
if(isset($_GET) & !empty($_GET)){
$id_product = $_GET['id_product'];
if(isset($_GET['quantity']) & !empty($_GET['quantity'])){ $quant = $_GET['quantity']; }else{ $quant = 1;}
$_SESSION['cart'][$id_product] = array("quantity" => $quant);
header('location: cart.php');
}else{
header('location: cart.php');
}
echo "<pre>";
print_r($_SESSION['cart']);
echo "</pre>";
?>
and some code of the cart.php
foreach ($cart as $key => $value) {
$cartsql = "SELECT * FROM product WHERE id_product=$key";
$cartres = mysqli_query($con, $cartsql);
$row = mysqli_fetch_assoc($cartres);
?>
<tr><form>
<td colspan="2"><?php echo $row['name'] ?></td>
<td><?php echo $row['price'].' €'; ?></td>
**<td><input type="number" class="quantity" name="quantity" value="<?php echo $value['quantity']; ?>"></td>**
<td><?php echo ($row['price']*$value['quantity']).' €'; ?> </td>
<td><img width="30" height="30" src="icons/delete.png" alt=""></td> </tr>
If i send to addcart an item of some quantity it's working.
the problem is I cannot change the quantity inside on cart.php, I know very few about Javascript.
Please any help how to do this ??
i did it with a submit form inside the cart :)
<form class="userform" method='get' name="change" action="addtocart.php">
<input type='hidden' name='id_product' value="<?php echo $row["id_product"]; ?>" />
<td><input size="5" type="number" name="quantity" value="<?php echo $value['quantity'] ?>" min="1" max="20" onchange="this.form.submit()"></td></form>

calculate loop fields with MySql php

I have an HTML table which is getting data from MySql.
existingbankproducts table is below:
I have 2 calculated fields which need to sum up the numbers that I get. The fields that are needed to calculate is Balance and MonthlyCommitment.
The code I use to get the result from MySql is below:
<?php
$stmt2 = $DB_con->prepare("SELECT * FROM applicantpersonaldetails apd "
. "INNER JOIN existingbankproducts ext ON apd.ApplicantID = ext.ApplicantID "
. "WHERE apd.AccountID =:accountId AND apd.applicantType ='main';");
$stmt2->bindParam(':accountId', $accountId, PDO::PARAM_INT);
//if account id data type is varchar change the last parameter to `PDO::PARAM_str`
$stmt2->execute();
if ($stmt2->rowCount() > 0) {
?>
<table>
<tr>
<th>Financial Institution</th>
<th>Product Type</th>
<th>Balance</th>
<th>Monthly Commitment</th>
</tr>
<?php
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
?>
<tr>
<td><input type = "text" name = "finanIns1" id = "finanIns1" value="<?php echo $row['FinanicalInstituion']; ?>" readonly></td>
<td>
<input list = "proTypeList" name = "proType1" id = "proType1" value="<?php echo $row['ProductType']; ?>"readonly >
</td>
<td id = "balance"><input type = "number" name = "balance1" id = "balance1" value="<?php echo $row['Balance']; ?>"readonly></td>
<td id = "MonthyComm"><input type = "number" name = "monthlyComm1" id = "monthlyComm1" value="<?php echo $row['MonthlyCommitment']; ?>"readonly></td>
</tr>
<?php
}
} else {
?>
<div class="">
<div class="alert alert-warning">
<span class="glyphicon glyphicon-info-sign"></span> No Data Found ...
</div>
</div>
<?php
}
?>
<?php
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
$totalBalance = 0;
$totalBalance += $row['Balance'];
$totalMonthlyComm = 0;
$totalMonthlyComm +=$row['MonthlyCommitment'];
?>
<tr>
<td>Total:</td>
<td><input readonly></td>
<td id="balance"><input type="number" name="totalBalance" id="totalBalance" value="<?php echo $totalBalance; ?>" min="0" readonly></td>
<td id="MonthyComm"><input type="number" name="totalMonthlyComm" id="totalMonthlyComm" value="<?php echo $totalMonthlyComm; ?>" min="0" readonly></td>
</tr>
<?php
}
?>
</table>
I am able to retrieve the data from MySql. However, it is not able to sum up the totalBalance and totalMonthlyComm at the end of my table.
You only need to loop through the database result only once:
<?php
$stmt2 = $DB_con->prepare("SELECT * FROM applicantpersonaldetails apd "
. "INNER JOIN existingbankproducts ext ON apd.ApplicantID = ext.ApplicantID "
. "WHERE apd.AccountID =:accountId AND apd.applicantType ='main';");
$stmt2->bindParam(':accountId', $accountId, PDO::PARAM_INT);
//if account id data type is varchar change the last parameter to `PDO::PARAM_str`
$stmt2->execute();
$totalBalance = 0;
$totalMonthlyComm = 0;
if ($stmt2->rowCount() > 0) {
?>
<table>
<tr>
<th>Financial Institution</th>
<th>Product Type</th>
<th>Balance</th>
<th>Monthly Commitment</th>
</tr>
<?php
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
$totalBalance += $row['Balance'];
$totalMonthlyComm +=$row['MonthlyCommitment'];
?>
<tr>
<td><input type="text" name="finanIns1" id = "finanIns1" value="<?php echo $row['FinanicalInstituion']; ?>" readonly></td>
<td><input list="proTypeList" name="proType1" id="proType1" value="<?php echo $row['ProductType']; ?>" readonly></td>
<td id="balance"><input type="number" name="balance1" id="balance1" value="<?php echo $row['Balance']; ?>" readonly></td>
<td id="MonthyComm"><input type="number" name="monthlyComm1" id="monthlyComm1" value="<?php echo $row['MonthlyCommitment']; ?>" readonly></td>
</tr>
<?php
}
?><tr>
<td>Total:</td>
<td><input readonly></td>
<td id="balance"><input type="number" name="totalBalance" id="totalBalance" value="<?php echo $totalBalance; ?>" min="0" readonly></td>
<td id="MonthyComm"><input type="number" name="totalMonthlyComm" id="totalMonthlyComm" value="<?php echo $totalMonthlyComm; ?>" min="0" readonly></td>
</tr>
</table>
<?php
} else {
?>
<div class="">
<div class="alert alert-warning">
<span class="glyphicon glyphicon-info-sign"></span> No Data Found ...
</div>
</div>
<?php
} ?>
Change your lines from while as :
<?php
$totalBalance = 0;
$totalMonthlyComm = 0;
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
$totalBalance += $row['Balance'];
$totalMonthlyComm +=$row['MonthlyCommitment'];
}
?>
<tr>
<td>Total:</td>
<td><input readonly></td>
<td id="balance"><input type="number" name="totalBalance" id="totalBalance" value="<?php echo $totalBalance; ?>" min="0" readonly></td>
<td id="MonthyComm"><input type="number" name="totalMonthlyComm" id="totalMonthlyComm" value="<?php echo $totalMonthlyComm; ?>" min="0" readonly></td>
</tr>

Multiple select checkbox to display the table record

I want to filter the table by using multiple select checkbox by selecting multiple Company Name and the table will display the record related to the selected checkbox. It only able to select one checkbox and display one related record only but it cannot multiple select checkbox.
<form name="frmSearch" id="frmSearch" method="post" action="">
<label>Company Name </label>
<select id="multiple-checkboxes" multiple="multiple" name="COMPANYNAME">
<?php
$query = mysqli_query($conn_connection, "SELECT * FROM sl_iv GROUP by COMPANYNAME");
while ($row = mysqli_fetch_assoc($query)) {
echo "<option value='".$row["COMPANYNAME"]."'".($row["COMPANYNAME"]==$_POST["COMPANYNAME"] ? " selected" : "").">".$row["COMPANYNAME"]."</option>";
}
?>
</select>
<br></br>
<button type="submit" id="submit" class="btn btn-info btn-sm"><span class="glyphicon glyphicon-search"></span> Search</button>
<a href="cust_due_list.php">
<button type="button" class="btn btn-success btn-sm"><span class="glyphicon glyphicon-refresh"></span> RESET</button>
</a>
<br></br>
<table id="table">
<center>
<thead>
<tr class="item-row">
<th width="15%" style="text-align:center"><span>Doc No.</span></th>
<th width="10%" style="text-align:center"><span>Due</span></th>
<th width="5%" style="text-align:center"><span>Age</span></th>
<th width="20%" style="text-align:center"><span>Customer Name</span></th>
<th width="10%" style="text-align:center"><span>Ammount</span></th>
<th width="10%" style="text-align:center"><span>Payment</span></th>
<th width="10%" style="text-align:center"><span>OutStanding</span></th>
</tr>
</thead>
</center>
<tbody>
<?php
if(isset ($_POST['COMPANYNAME']))
{
$COMPANYNAME = $_POST['COMPANYNAME'];
$fetch = "SELECT sl_iv.DOCDATE, ar_iv.DUEDATE, payment_terms.terms, sl_iv.DOCNO, sl_iv.COMPANYNAME, ar_iv.DOCAMT, ar_iv.PAYMENTAMT FROM `sl_iv` Inner Join `ar_iv` On ar_iv.DOCNO = sl_iv.DOCNO Inner Join `payment_terms` On ar_iv.TERMS = payment_terms.id WHERE sl_iv.COMPANYNAME = '".$COMPANYNAME."' or sl_iv.DOCDATE <= '".$from."'";
$result = mysqli_query($conn_connection,$fetch)or die("MySQL error: " . mysqli_error($conn_connection) . "<hr>\nQuery: $fetch");
}
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$docamt = $row['DOCAMT'];
?>
<tr class="item-row">
<td>
<input type="text" style="text-align:center; font-size:15px" class="form-control input-sm DocNo" id=DocNo0 " name="DocNo " value="<?php echo htmlspecialchars($row[ 'DOCNO']);?>" readonly></td>
<td>
<input type="text" style="text-align:center; font-size:15px" class="form-control input-sm DueDate" id="DueDate0" name="DueDate" value="<?php echo htmlspecialchars($row['DUEDATE']);?>" readonly>
</td>
<td>
<input type="text" style="text-align:center; font-size:15px" class="form-control input-sm DateAge" id="DateAge0" name="DateAge" value="<?php echo $dateage;?>" readonly>
</td>
<td>
<input type="text" style="text-align:center; font-size:15px" class="form-control input-sm CompanyName" id="CompanyName0" name="CompanyName" value="<?php echo htmlspecialchars($row['COMPANYNAME']);?>" readonly>
</td>
<td>
<input type="text" style="text-align:right; font-size:15px" class="form-control input-sm TotalAmt" id="TotalAmt0" name="TotalAmt" value="<?php echo htmlspecialchars($row['DOCAMT']);?>" readonly>
</td>
<td>
<input type="text" style="text-align:right; font-size:15px" class="form-control input-sm payment" id="payment0" name="payment" value="<?php echo htmlspecialchars($row['PAYMENTAMT']);?>" readonly>
</td>
<td>
<input type="text" style="text-align:right; font-size:15px" class="form-control input-sm Total_Outstanding" id="Total_Outstanding0" name="Total_Outstanding" value="<?php echo number_format((float)$outstanding, 2, '.', '');?>" readonly>
</td>
</tr>
<?php
}
} else {
echo "0 results";
}
?>
</tbody>
</table>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#multiple-checkboxes').multiselect();
});
</script>
When you receive multiple-select POST it cames as array, so you should use "IN" operator in your mysql request instead of comparison.
Try to change one part of your code:
if(isset ($_POST['COMPANYNAME'])) {
$COMPANYNAME = $_POST['COMPANYNAME'];
$COMPANYNAME = is_array($COMPANYNAME) ? $COMPANYNAME : [$COMPANYNAME];
$companiesParam = '\''. join("', '", $COMPANYNAME) . '\'';
$fetch = "SELECT sl_iv.DOCDATE, ar_iv.DUEDATE, payment_terms.terms, sl_iv.DOCNO, sl_iv.COMPANYNAME, ar_iv.DOCAMT, ar_iv.PAYMENTAMT FROM `sl_iv` Inner Join `ar_iv` On ar_iv.DOCNO = sl_iv.DOCNO Inner Join `payment_terms` On ar_iv.TERMS = payment_terms.id WHERE sl_iv.COMPANYNAME IN (".$companiesParam.") or sl_iv.DOCDATE <= '".$from."'";
$result = mysqli_query($conn_connection,$fetch)or die("MySQL error: " . mysqli_error($conn_connection) . "<hr>\nQuery: $fetch");
}

How can I add rows in my HTML table equal to the number of entries I have in Mysql DB?

Also, how can I access the <td> for each value?
This is my table in HTML:
<table class="inventory" style="float:left; position:relative;">
<tbody>
<tr>
<th>Name</th>
<th>Rate</th>
<th>OT</th>
<th>Leaves</th>
<th>Total</th>
</tr>
<tr>
<td>
<input type="text" placeholder="Name"/>
</td>
<td>
<input type="text" placeholder="Rate"/>
</td>
<td>
<input type="text" placeholder="OT"/>
</td>
<td>
<input type="text" placeholder="Leaves"/>
</td>
<td>
<input type="text" placeholder="Total"/>
</td>
</tr>
<tr>
<td>
<input type="text" placeholder="Name"/>
</td>
<td>
<input type="text" placeholder="Rate"/>
</td>
<td>
<input type="text" placeholder="OT"/>
</td>
<td>
<input type="text" placeholder="Leaves"/>
</td>
<td>
<input type="text" placeholder="Total"/>
</td>
</tr>
</tbody>
</table>
How can I add rows in my HTML table equal to the number of entries I have in Mysql DB?
I am assuming your database connection as $con. Place your database table name and column name in appropriate place.
<table class="inventory" style="float:left; position:relative;">
<tbody>
<tr>
<th>Name</th>
<th>Rate</th>
<th>OT</th>
<th>Leaves</th>
<th>Total</th>
</tr>
<?php
$query = mysqli_query($con,"SELECT * FROM tableName");
while($row = mysqli_fetch_array($query,MYSQLI_ASSOC))
{?>
<tr>
<td>
<input type="text" placeholder="Name" value="<?php echo $row['Name_Column_name']?>"/>
</td>
<td>
<input type="text" placeholder="Rate" value="<?php echo $row['Rate_Column_name']?>"/>
</td>
<td>
<input type="text" placeholder="OT" value="<?php echo $row['OT_Column_name']?>"/>
</td>
<td>
<input type="text" placeholder="Leaves" value="<?php echo $row['Leaves_Column_name']?>"/>
</td>
<td>
<input type="text" placeholder="Total" value="<?php echo $row['Total_Column_name']?>"/>
</td>
</tr>
<?php }?>
</tbody>
</table>
You can use this coding adn edit it as per your requirement
<table>
<tr>
<td>Name</td>
<td>Rate</td>
<td>OT</td>
<td>Leaves</td>
<td>Total</td>
</tr>
<?php
$total_row=mysql_num_rows(mysql_query("SELECT * FROM table_name"));
$q="SELECT * FROM table_name";
$run=mysql_query($q);
if($total_row > 0)
{
while($row1=mysql_fetch_assoc($run))
{
$Name=$row1['Name'];
$Rate=$row1['Rate'];
$OT=$row1['OT'];
$Leaves=$row1['Leaves'];
$Total=$row1['Total'];
?>
</tr>
<tr>
<td><?php echo $Name;?></td>
<td><?php echo $Rate;?></td>
<td><?php echo $OT;?></td>
<td><?php echo $Leaves;?></td>
<td><?php echo $Total;?></td>
</tr>
<?php }
}?>
</table>
Try with something like this:
$sql = "SELECT..."; //Add your query. Presumed you have 'name' column
$result = mysql_query($sql);
echo '<table class="inventory" style="float:left; position:relative;">';
echo '<thead>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<th>'.$row["name"].'</th>';
echo '</tr>';
}
echo '</thead>';
echo '<tbody>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>';
echo '<input type="text" placeholder="'.$row["name"].'"/>';
echo '</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';

Categories