Associating HTML's deleteRow() with a table generated by PHP - php

I have the following PHP code to generate a table where there are rows whose columns have the following attributes: "id", "lastname", and "firstname". I want to add a button for each of the rows that deletes the respective row and have this line to attempt to do so: echo '<td><input type="button" value="Delete" onclick="deleteRow('+$i+')"></td>'; in the following code. However, it's printing the value of $i (1,2,3,4,... which are the row numbers I want associated with the buttons) instead of having delete buttons dedicated to each row (with the follow code below, it doesn't create any buttons unless I specifically remove the '+$i+' part). What is the issue?
<table>
<tr>
<td></td>
<td>id</td>
<td>Last Name</td>
<td>First Name</td>
</tr>
<?php
$i = 1;
foreach ( $names['result'] as $a ){ // $a is an array
echo '<tr>';
echo '<td><input type="button" value="Delete" onclick="deleteRow('+$i+')"></td>'; // issue is here
echo '<td>' . $q['id'] . '</td>';
echo '<td>' . $q['lastName'] . '</td>';
echo '<td>' . $q['firstName'] . '</td>';
echo '</tr>';
}
?>
</table>

The . is the string concatenation operator in php language whereas the + is a concatenation operator in javascript language.
You should use onclick="deleteRow('.$i.')"
And then, just before ending the loop, just use a $i++;

Related

Database rows not displaying fully in HTML table

I am attempting to display mySQL data in a HTML table through php. The first row is displaying correctly, however the other row sets are not being organised and displayed in my table, rather just echoing out at the bottom of the container with no structure.
I think that since the data is being displayed, albeit not in the table, that my query is correct, im just unsure on how to proceed.
Is this an issue with my table structure?
I tried adding a second:
echo '<td>' . $data['studentNumber'] . '</td><td>' . $data['handle'] . '</td><td>' . $data['email'] . '</td>';
underneath my first echo, but it just duplicated everything.
Here is the entire code in question: Screenshot Here
<div class="container-fluid">
<div class="row">
<div class="col-md details">
<p class="details_title"></p>
<?php
$getAllStudentsTable = "SELECT * FROM users WHERE accessLevel = 3";
$result = (mysqli_query($conn, $getAllStudentsTable));
echo '<table class="table">
<thead class="thead-dark">';
echo' <tr>
<th scope="col">Student Number</th>
<th scope="col">Handle</th>
<th scope="col">Email Address</th>
</tr>
</thead>'; //table headers
while ($data = mysqli_fetch_array($result)) {
echo' <tbody> <tr>';
echo '<td>' . $data['studentNumber'] . '</td><td>' . $data['handle'] . '</td><td>' . $data['email'] . '</td>';
echo'</tr> </tbody> </table>';
}
?>
Can anyone point me in the right direction on this?
(I am relatively new to PHP, SO and this is the first attempt ever at trying to display database data into an HTML table.)
I have attached a link for a screenshot of the issue (Not yet allowed to post pictures lol).
Thanks!
You're echoing most of the table structure in your loop, where you should just be echoding the rows. As a necessary debugging step, take a look at the View Source in your browser and see what the table structure is. You'll find multiple <tbody> elements and multiple closing </table> tags, confusing the browser.
Basically, remove the various <tbody> and <table> tags from your loop and just echo them around the loop. Something like this:
echo '<tbody>';
while ($data = mysqli_fetch_array($result)) {
echo '<tr>';
echo '<td>' . $data['studentNumber'] . '</td><td>' . $data['handle'] . '</td><td>' . $data['email'] . '</td>';
echo '</tr>';
}
echo '</tbody></table>';
All you want to repeat in the loop is each <tr> element and its children.

PHP foreach using $variable->property

I have some code that runs reports from $results returning from mysql query.
The queries are relatively standard, but their total number is dynamic. So far I have static HTML where it has the same code repeated, but thats only if ok the number of queries == the number of markup repetitions.
So, I am trying to implement a new foreach loop that will determine how many "queries" there are, and only markup for each one, and then $total at the end.
To date I have had static php foreach loop like this, works well.
<div class="row">
<div class="col-xs-12">
<table class="table table-striped">
<thead>
<tr>
<th>Year</th>
<th>Month</th>
<th>Item</th>
<th class="text-right">Minimum</th>
<th class="text-right">Maximum</th>
<th class="text-right">Change</th>
</tr>
</thead>
<tbody>
<?php foreach ($results as $result) :
if ($result->id == 151){
echo '<tr>';
echo '<td>', $result->Year, '</td>';
echo '<td>', $result->Month, '</td>';
echo '<td class="text-centre">', $result->name, '</td>';
echo '<td class="text-right">', $result->min, '</td>';
echo '<td class="text-right">', $result->max, '</td>';
echo '<td class="text-right">', $result->cumulative, '</td>';
$thirdtotal += $result->change;
$total += $result->change;
echo '</tr>';
}
endforeach; ?>
Where I am stuck is, do i put the above inside another for each loop? My thought is, if a query exists, it will have an "id" field in the array, so for the number of "id", thats how many outputs you'll get.
<?php foreach ($results as $key => $value;) :
{
echo '<tr>';
echo '<td>' $value, '</td>';
echo '</tr>';
}
endforeach; ?>
This piece of test code doesnt work, am I using the key value correctly? Is it the correct approach to solve this problem and reduce the amount of php in the controller?
Thanks

Delete from html table made by database PHP

Here is the table below that I'm trying to delete rows out of:
<form method="POST" >
<table class="sortable">
<thead>
<tr>
<th id="makehead">Make </th>
<th id="modelhead">Model </th>
<th id="idhead">Delete </th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
foreach ($carArray as $k => $carInfo) {
$i++;
echo '<tr>';
if ($i % 2) {
echo '<td class="make">' . $carInfo['make'] . '</td>
<td class="model">' . $carInfo['model'] . '</td>
<td class="id"><input type="checkbox" name="id" value="' . $carInfo['id'] . '">' . $carInfo['id'] . '</td>';
} else {
echo '<td class="makelight">' . $carInfo['make'] . '</td>
<td class="modellight">' . $carInfo['model'] . '</td>
<td class="idlight"><input type="checkbox" name="id" value="' . $carInfo['id'] . '">' . $carInfo['id'] . '</td>';
}
}
?>
</tr>
</table>
</tbody>
<td>
<input Onclick="return ConfirmDelete();" name="delete" type="submit" id="delete" value="Delete"></input>
</td>
</table></form>
As you can see i'm using checkboxes to tick each row then the delete button will have a confirm message then should delete but it doesn't here is my if statement:
if ($_REQUEST['delete']) {
$dbid = $_REQUEST['id'];
$db->setdbid($dbid);
So when this wasn't working I had a look on here and on other questions people said I need a setter function so i did this: EDIT: this is my class file.
public function setdbid($dbid){
$this->dbid=$dbid;
}
for this main function to delete things:
public function delete($dbid) {
try {
$sql = "DELETE FROM cars WHERE id = '$dbid'";
$this->db->exec($sql);
echo "Car has been deleted.";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
So that's all the relevant code I think, please help me if you can.
You just have to replace some piece of code in PHP :
if ($_REQUEST['delete']) {
$dbid = $_REQUEST['id'];
$db->delete($dbid); //Assuming delete is well a $db method, else replace it by the correct delete call
}
As you are using checkboxes with the same name, you have to change it so it's an array (and this way you'll be able to delete multiple rows at once) :
<td class="id"><input type="checkbox" name="ids[]" value="' . $carInfo['id'] . '">' . $carInfo['id'] . '</td>';
Then in your php code, treat this data as such :
if ($_REQUEST['delete']) {
foreach($_REQUEST['ids'] as $id){
$xxx->delete(intval($id)); //convert to integer to avoid sql injection.
}
}
Note that you don't need to set $db->setdbid since you pass that id as a parameter of your delete method.

get and display multiple checkbox values from database using php

i having two check boxes when i am selecting both check boxes i want to show the value related to both from database ,but now i able to print only one id of check boxes i want to show both data can anyone help hoe to show both a value ,Below is my code:
html
<input type="submit" name="Update" src="/image/exporttt.png" style="margin:0px;cursor:pointer">
<tbody>
<?php
$clientid=$_GET['clientid'];
if($clientid!=""){
$sql = mysql_query("SELECT * FROM clientnetworkpricehistory");
while($rows=mysql_fetch_array($sql))
{
if($alt == 1)
{
echo '<tr class="alt">';
$alt = 0;
}
else
{
echo '<tr>';
$alt = 1;
}
echo '
<td id="CPH_GridView1_clientid" style="width:140px" class=" clientid '.$rows["net_id"].'">'.$rows["clientid"].'</td>
<td id="CPH_GridView1_country" style="width:160px" class=" country '.$rows['net_id'].'">'.$rows["country"].'</td>
<td id="CPH_GridView1_networkname" style="width:156px" class="networkname '.$rows["net_id"].'">'.$rows["networkname"].'</td>
<td id="CPH_GridView1_mccmnc" style="width:250px" class=" mcc'.$rows["net_id"].'">'.$rows["mcc"].'</td>
<td id="CPH_GridView1_mccmnc" style="width:250px" class=" mnc '.$rows["net_id"].'">'.$rows["mnc"].'</td>
<td id="CPH_GridView1_oldprice" style="width:320px" class=" oldprice '.$rows["net_id"].'">'.$rows["pricefrom"].'</td>
<td id="CPH_GridView1_newprice" style="width:129px" class=" newprice '.$rows["net_id"].'">'.$rows["priceto"].'</td>
<td id="CPH_GridView1_oldroute" style="width:143px" class="oldsupplierroute '.$rows["net_id"].'">'.$rows["routefrom"].'</td>
<td id="CPH_GridView1_newroute" style="width:143px" class=" newsupplierroute '.$rows["net_id"].'">'.$rows["routeto"].'</td>
<td id="CPH_GridView1_comments" style="width:143px" class=" comments '.$rows["net_id"].'">'.$rows["status"].'</td>
<td id="CPH_GridView1_from" style="width:143px" class=" fromdate '.$rows["net_id"].'">'.date('d.m.Y H:i', $rows["datetime"]).'</td>
<td style="width:65px" class=" '.$rows["net_id"].'"><input type="checkbox" name="chk1" value=" '.$rows["net_id"].'"/></td>
</tr>';
}
}
?>
</tbody>
jssearch.php
<?php
//connecting to db
$variable=$_POST['chk1'];
foreach ($variable as $variablename)
{
$sql_select="SELECT * from clientnetworkpricehistory where net_id=$variablename";
$queryRes = mysql_query($sql_select);
print"$sql_select";
}
echo "<table border='1'>
<tr>
<th>country</th>
<th>networkname </th>
<th>mcc</th>
<th>mnc</th>
<th>datetime </th>
</tr>";
while($row = mysql_fetch_array($queryRes))
{
echo "<tr>";
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['networkname'] . "</td>";
echo "<td>" . $row['mcc'] . "</td>";
echo "<td>" . $row['mnc'] . "</td>";
echo "<td>" . $row['datetime'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
my out put was(i am checked two checkboxes and i am trying to print two check boxes id it only showing one can any one help me how to do that)
56
Warning: Invalid argument supplied for foreach()
Use name="chk1[]" in your HTML so the checkboxes will be posted as an array.
Besides that:
The mysql_* functions are deprecated, consider using mysqli_* or PDO
You are vulnarable to SQL-injection on your where net_id=$variablename"
I agree with Peter but you also might wanna fix this little typo:
'.$rows['net_id'].'">'.$rows["country"].'
That's line 2 of that large echo you have with all the <td>s. The $rows['net_id'] should be double quotes.
But you knew that...:)

Display information from MySQL

I have a code that display on the page the information of a specific user, from a MySQL table. However, the informaiton is all displayed on a simple line, back to back. What I want, is to display the information of each line in diffrent blocks. So my question: how can I «brake» the line, to create many diffrent blocks of information, that I can put were I want on my page?
<?php
while ($row = mysql_fetch_array($query)) {
echo $row['Column A'] . " " . $row['Column B'] . " " . $row['Column C'] . " ";
} ?>
First of all you should change your mysql_* functions to another functions like PDO & mysqli
About your question is how to generate HTML from your DB data there are multiple of ways
One could be like this
<?php
while ($row = mysql_fetch_array($query)) {
?>
<h1><?php echo $row['columnA']; ?></h1>
<div class="myclass"><?php echo $row['columnb']; ?></div>
<img src="<?php echo $row['columnC']; ?>">
<?php
} ?>
Two could be
<?php
while ($row = mysql_fetch_array($query)) {
$str = "";
$str .= "<h1>".$row['columnA']."</h1>";
$str .= '<div class="myclass">'.$row['columnb'].'</div>';
$str .= '<img src="'.$row['columnC'].'">';
echo $str;
<?php
} ?>
Or you can use a FW wich make it simpler for you
Or you can use a templating library which is the best way for you if you are not going to use a Framework
check out mustache https://github.com/bobthecow/mustache.php
Of course you can change the HTML structure
I hope this can help :)
I think a table might be what you are looking for...
(Don't forget to change to mysqli* as #Sedz mentioned in his answer)
<table border="1">
<?php
while ($row = mysqli_fetch_array($query)) {
echo '<tr>';
echo '<td>' . $row['Column A'] . '</td>';
echo '<td>' . $row['Column B'] . '</td>';
echo '</tr>';
echo '<tr>';
echo '<td></td>';
echo '<td>' . $row['Column C'] . '</td>';
echo '</tr>';
};
?>
</table>
Arrange the results in rows/cells as you see fit...
Perhaps the best way is you pass the results into an array
$data = array();
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
And the break you are talking about
foreach ($data as $value) {
echo "$value<br>";
}
It is simple user2619310!
Add "\n" in your line.
Example:
<?php
while ($row = mysql_fetch_array($query)) {
echo $row['Column A'] . " " . $row['Column B'] . " " . $row['Column C'] . "\n";
}
?>
Bye! :-D
How you break the lines can vary depending on what your objectives are and where you're going to use them. Here are some ways of having information on different lines:
Use the br tag at the end of each field.
Use DIVs to contain each row.
Use a table for each row.
DIVs will be the best if you're looking at different browsers and efficient sizing. But tables are also easy to implement for certain things.
Here's how I'd break the rows using tables.
<table>
<?php while ($row = mysql_fetch_array($query)): ?>
<tr>
<td>Column A label</td>
<td><?php echo $row['ColumnA']; ?></td>
</tr>
<tr>
<td>Column B label</td>
<td><?php echo $row['ColumnB']; ?></td>
</tr>
<tr>
<td>Column C label</td>
<td><?php echo $row['ColumnC']; ?></td>
</tr>
<?php endwhile; ?>
</table>
I don't have the slightest clue about your DB table structure but going by what you've shown, I have included an example. This is not tested but it should be good.
Also note the alternative PHP syntax for the while loop.

Categories