Deleting multiple records(rows) from tables using checkboxes - php

Trying to delete multiple rows using check-boxes. At first i'm generating table of contents with checkbox column. Then posting data to php side. The problem is, php side returning back to the current page. It means that all done successfully and page returned user back. But no success. There is no error in php logs, and MySQL problem. I tried print_r ($_POST['checkbox']); die(); after $delete=$_POST['delete'];. It gave me result something like that Array ( [0] => on [1] => on ) what's wrong with my code?
My HTML markup looks like that
<?php
$result = $db->query("SELECT id, name, showinmenu FROM menu") ;
$num=$result->num_rows;
if ($num>0) {
?>
<form method="post" action="processor/dbdel.php">
<div style="overflow-y: auto; overflow-x: hidden; height:500px">
<table id="list" class="features-table">
<thead>
<tr>
<th>#</th>
<th style="min-width:80px;" class="name">Ad (menyuda işlənən)</th>
<th>Sil</th>
</tr>
</thead>
<tbody>
<?
while ($row = $result->fetch_object()) {
echo '<tr>
<td>'.$row->id.'</td>
<td>'.$row->name.'</td>
<td><input type="checkbox" name="checkbox[]" method="post" value"'.$row->id.'" id="checkbox[]" "/></td>
</tr>';
}
// when the loop is complete, close off the list.
echo "</tbody> <tr id='noresults'>
<td style='text-align:center' colspan='9'>Nəticə yoxdur</td>
</tr></table>
</div>
<p style='text-align:center;'>
<input id='delete' type='submit' name='delete' value='Seçilənləri sil'/> </p>
</form>";
}
?>
And here is my PHP code
<?php
require '../../core/includes/common.php';
$delete=$_POST['delete'];
if($delete) // from button name="delete"
{
if (is_array($_POST['checkbox']))
foreach($_POST['checkbox'] as $del_id) {
$del_id = (int)$del_id;
$result=$db->query ("DELETE FROM menu WHERE id = '$del_id'") or die($db->error);
$result2=$db->query ("DELETE FROM pages WHERE id = '$del_id'") or die($db->error);
}
if($result2)
{
header("location:".$wsurl."admin/?page=db");
}
else
{
echo "Error: ".$db->error;
}
}
?>

Your code is an absolute disaster.
1) Using echo with repeated string concatenation to output html. Look up HEREDOCs, double-quoted strings, or simply breaking out of PHP-mode (?>) to output html.
2) Checking for POST by looking for form fields. If you want to make sure you're in a POST situation, then do if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... } instead. This is 100% reliable, and does not depend on the presence (or absence) of particular form fields. If the data was submitted via post, this statement will evaluate to true, ALWAYS.
3) You are blindly embedding user-provided data into SQL query strings. Read up about SQL injection attacks, then consider what happens if someone hacks your form and submits a checkbox value of ' or 1' - say goodbye to the contents of your checkbox table.
4) You appear to have a stray " in your checkbox output line:
[...snip...] method="post" value"'.$row->id.'" id="checkbox[]" "/></td>
^--here
which is almost certainly "breaking" your form and causing subsequent tag attributes to be misinterpreted.
5) on the plus side, I'll have to give you this much - you are at least checking for query errors on your two delete queries, which is always nice to see. However, that's a minor plus in a huge field of negatives.

Related

Using a PHP generated webform and mySQL to update multiple rows in a table

I have created a database to store results in a competition along witha php generated web-page that lists all the competitors followed by a textbox in which to record their score.
When I press the submit button I want it to update all of the rows in the table.
I'm new to php and mySQL, I can do it for one of them at a time but I don't want them to have to press 30+ individual submit buttons to handle each row.
The following code generates the form:
<?php
$field_event_id = $sports_day_id = "";
if ( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' )
$field_event_id = $_POST["field_event"];
$sports_day_id = $_POST["sportsday"];
$query = "SELECT * FROM student JOIN participants ON student.student_ID = participants.student_ID WHERE `Field_Event_ID`= $field_event_id";
$result = mysqli_query( $dbc, $query ) ;
echo '<body>';
if ( mysqli_num_rows( $result ) > 0 )
{
echo'<header> <h1> Please enter the results below </h1> </header>';
echo '<table align="center" border="1" cellpadding="10px" bgcolor="#DCF8FE">
<tr>
<th>Forename</th>
<th>Surname</th>
<th>Year Group</th>
<th>Score</th>
</tr>
<tr>';
while ( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ))
{
echo '<form action="Add_Scores_Field_Event_Register.php" method="post">
<td> <strong>' . $row['Forename'] .'</strong><br> </td>
<td> <strong>' . $row['Surname'] .'</strong><br> </td>
<td> <strong>' . $row['Year_Group'] .'</strong><br> </td>
<td> <strong> <input type="text" name="notes_input"> </strong><br> </td>
</tr>
</form>';
}
echo '</table>';
echo '<p><input type="submit" value="Enter scores" ></p>';
}
else
{
echo '<p>There are currently no students in this event.</p>' ;
}
{
# Close database connection.
mysqli_close( $dbc ) ;
}
# close body section.
echo '</body>';
# close HTML section.
echo '</html>';
mysqli_close($dbc);
?>
According to this post you can set the name attribute of elements to an array.
<input type="text" name="inputs[]" value="bob">
<input type="text" name="inputs[]" value="jim">
If you submit this through a form. You should be able to access the values like:
$_POST["inputs"][0]; // bob
$_POST["inputs"][1]; // jim
So, if you output your information inside a form and setup the name attributes for the scores properly. When you submit the form, you should be able to grab all the scores (editted or not) and update your database with the values.
You will have to keep track of which record in the database to change.
The code I provided is untested; however, according to the linked post, it should work.
Don't forget to learn about prepared statements as Alex Howansky had commented. These are really important.
If you try this out, you would need to move your form tags to wrap the entire table; instead of, particular rows.
EDIT:
With a little more though I see 2 solutions:
Place the student ID inside a hidden tag and use the name attribute to send it along with the other data.
<input type="hidden" name="studentIds[]" value="<place student id here>">
I would place the input tag in the td for your forename; because, it is the first td and one of the tds that uniquely represents the row.
OR
Use the Student ID as the index for your index and the score as the value.
<input type="text" name="notes_input[<place student id here>]">
You can then iterate through notes_input and get the key and value:
foreach ($array as $key => $value) {
//code
}
See documentation for more information.

Sending a SQL command with one click of an HTML button through PHP

So, I have a basic PHP site that brings up a list of salespeople from a MySQL server when a selection from a drop-down box is submitted. I've set up a button to appear next to each result, and I want a php script to run when the button is clicked using MySQL data from that specific result. Everything works except the button that runs the second MySQL query. Here's an example of the table after the first query:
<table border="1">
<tr>
<td>Last name</td>
<td>First Name</td>
<td>Job Title</td>
<td>City</td>
<td>Client List</td>
</tr>
<tr>
<td>Bondur</td>
<td>Gerard</td>
<td>Sale Manager (EMEA)</td>
<td>Paris</td>
<td>
<form method="POST" action="empLookup.php">
<input type="submit" name="empLookup" value="Look up clients"
</td>
</tr>
</table>
By clicking on the button I would run a MySQL command like 'SELECT clients FROM blah WHERE employeeNumber = ?'
I don't have a problem with any of this except passing the value from the button to the PHP script.
This is what my PHP code looks like for handling the form submission and display of results. The button(s) in question are in the HTML table in the foreach loop.
<?php #this is the default php file for looking up Employees
$page_title = 'Our Associates by City';
require ('./pdoConn.php');
$sql = "SELECT DISTINCT city from Offices";
echo '<h1>Our Associates by City</h1>';
Type in a Name to view Years</a><br>';
//create the form
echo 'Please select a year: <br>';
echo '<form action="index.php" method="post">';
echo '<select name= "city">';
foreach($conn->query($sql) as $row)
{
//each option in the drop down menu is each and every year
//brought up by the query
echo '<option value ="'. $row['city'].' ">'. $row['city']. '</option>';
} //end of foreach
echo '</select>'; //end drop down menu
//now to create the submit button
echo '<br><input type="submit" name="submit" value="List"><br>';
echo '</form>'; //end of form
//This if statement runs when the submit button is clicked
if ($_SERVER[REQUEST_METHOD] == 'POST')
{
$flit = $_POST[city]; //the city variable from the HTML form will be used
echo '<br><br>';
$sql2 = "SELECT employeeNumber,lastName,firstName,jobTitle,city
FROM Employees,Offices
WHERE Employees.officeCode = Offices.officeCode AND city = ?";
$stmt = $conn->prepare($sql2);
$stmt->execute(array($flit));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo 'Contact any of our local staff: <br>';
//create a table of employees
echo '<table border="1"><tr><td>Last name</td><td>First Name</td>';
echo '<td>Job Title</td><td>City</td></tr>';
//time to populate the table, this loop runs for each entry
foreach($rows as $r)
{
echo '<tr><td>'.$r[lastName].'</td><td>'.$r[firstName].'</td><td>';
echo $r[jobTitle].'</td><td>'.$r[city].'</td><td>';
echo '<form method="POST" action="empLookup.php">';
//now to make the button which will search the employee's client list
echo '<input type="submit" name="empLookup" value="Look up clients"</td></tr>';
} //end foreach
echo '</table>';
} //end if server request post thing
?>
I does not completely understood your exact requirement but I think you want employee number into your button if this is your requirement then you can simply check this code
`echo '<input type="submit" name="empLookup" value="'.$r['emp_id_from_database'].'"</td></tr>';`
From your html code, your form looks empty.
You need to add the data to your html form. If you want to avoid the user to see you can use fields. Like it was in the comments said, use $variableName instead of ? in your query. Don't forget use \"$variableName\" to avoid mysql injections.
I took a second reading of your code: You realy should read a php book completly before you program stuff for productive company websites. There are beginner mistakes in your code. And some beginner mistakes leads to insecure websites. I hope this doesn't look an offense, but like an advise.

How to update a database value with an imagebutton in php

I am working on an php file, winch shows an table with values of the database. every row has an imagebutton at the end, which should change the status, displayed with an image.
so I think short function of it all must be, on click go to script go to php or jQuery?
the buttons also have to give the id of the user to the next script or function, or os there a better way?
here is my basic approach, with no functionality, for the moment
in index.php
include("function.php");
while ($row_user = mysql_fetch_assoc($result_user)) {
$sqle = mysql_query("
SELECT COUNT(*) FROM
places2user
WHERE
user = '".mysql_real_escape_string($row_user['ID'])."'
");
$res23 = mysql_fetch_array($sqle);
echo <table>
echo <tr>
echo "<td>".$row_user['ID']." </td><td><input type=\"image\" src=\"images/".htmlentities($row_user['receive'], ENT_QUOTES)."\" id=\"status\" name=\"status\" ></td>
echo </tr>
echo </table>
}
there is also a function.php, with a changestatus($id) function, which updates the database values, but I think, this is not the right way to code this.
While programming, don't rely on javascript only. I always create form using just html and css, make sure it works, and than add fancy stuff with jQuery or so. This way you know the form will also work without javascript (great for users without it).
But to come to your question:
if you use this, it should do what you want:
<?php echo "<form action='?' method='post'>
<table>
<tr>
<td>".$row_user['ID']." </td>
<td><input type='hidden' name='userId' value='".$row_user['ID']."'/>
<input type=\"image\" src=\"images/".htmlentities($row_user['receive'], ENT_QUOTES)."\" id=\"status\" name=\"status\" ></td>
</tr>
</table></form>";

First record from database is not displayed?

Trying to work on a clients site and I am having a bit of difficulty. When I have no entries in the database, it catches at if(!row) and displays the message. This part works fine. My issue is when I have entries in the db, they do not display. I know the while loop works because I have several pages running a similar loop. In fact, this loop was copied from another page that displays this entry's information on a public page.
I know this site is mainly for questions, but I think I just need a fresh pair of eyes to look at my code(I've been coding for over 12 hours and I'm a bit tired). A lot of the code below is from a previous web designer and if it were up to me, I would just rewrite the entire site because the code is "out of date", but the client just wants me to improve on it. Any help would be greatly apprecieated.
$row = mysql_fetch_array($result);
if (!$row) {
echo '<tr><td bgcolor="ffffff" colspan="3"><font face="arial,helvetica" size="2" color="000000">There are no entries at this time, check back later.</font></td></tr>';
} else {
while ($row = mysql_fetch_array($result)) {
echo '<tr>
<td bgcolor="ffffff"><font face="arial,helvetica" size="2" color="000000">$date - $row["theme"]</font></td>
<td bgcolor="ffffff" align="center">
<form action="dsp_modifyposition.php">
<input type="hidden" name="specialID" value="$row["specialID"]">
<input type="hidden" name="theme" value="$row["theme"]">
<input type="submit" value=" Modify ">
</form>
</td>
<td bgcolor="ffffff" align="center">
<form action="act_deleteposition.php" onsubmit="return confirm(\'Are you sure you want to delete this event: $date \')">
<input type="hidden" name="specialID" value="$row["specialID"]">
<input type="hidden" name="theme" value="$row["theme"]">
<input type="submit" value=" Delete ">
</form>
</td>
</tr>';
}
}
When you call mysql_fetch_array for the first time, the mysql result pointer is moved to the next row. Because nothing is done with this row, this first row does not get displayed. What you want is mysql_num_rows to check how many rows are in the resultset. As a side-note, I would suggest using mysql_fetch_assoc if you're not using the numeric indices.
if (!mysql_num_rows($result)) {
echo '...';
} else {
while ($row = mysql_fetch_assoc($result)) {
echo '...';
}
}
Change your first lines to this:
$cnt = mysql_num_rows($result)
if (!$cnt) {
echo '<tr><td bgcolor="ffffff" colspan="3"><font face="arial,helvetica" size="2" color="000000">There are no entries at this time, check back later.</font></td></tr>';
} else {
....
Your if() statement seems flawed. The statement:
$row = mysql_fetch_array($result);
will fetch a row and move the pointer in $result to the next row, so your while will start at the second row. If your query returns only one row, you're effectively calling mysql_fetch_array() twice and skipping over the data returned.
You should find some other way of checking if you have results (possibly with mysql_num_rows()).

How do I post back to a database?

I am new to PhP and MySQL and now having trouble displaying certain records. I have records pf list of students and their year level stored in a database. I was able to display all of them in a webpage. Now I have one textbox and a button and what I wanted to do is when I enter for example "1" on the textbox and click the button, what will appear on my page will be the records of all the first year students only.
Somehow I need to change it so that when the year is posted back then it changes the sql to limit the information displayed.
Any suggestions or links to some examples will be much appreciated. Here is my code.
<form name="form1" method="post" action="">
<div align="center">
<?php
include("dbcon.php");
$query="select * from student order by year, studname";
$result=#mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result)>0)
{
?>
<label>
<input type="text" name="txtyear" id="txtyear">
<input type="submit" name="btnyear" id="btnyear" value="Submit">
</label>
<table width="75%" border="1">
<tr>
<td align="center" width="20%"><strong>Student Number</strong></td>
<td align="center" width="27%"><strong>Name</strong></td>
<td align="center" width="23%"><strong>Course</strong></td>
<td align="center" width="30%"><strong>Year Level</strong></td>
</tr>
<?php
while($row=mysql_fetch_array($result))
{echo "<tr>";
echo "<td>".$row['studno']."</td>";
echo "<td>".$row['studname']."</td>";
echo "<td>".$row['course']."</td>";
echo "<td>".$row['year']."</td>";
echo "</tr>";
}
?>
</table>
<?php
}
else
echo "no records found";
?>
</div>
</form>
You need a WHERE clause. A very basic example might look like this:
$year = mysql_real_escape_string($_POST['year']);
$query = SELECT * FROM student WHERE year = $year ORDER BY studname";
NB: Look into the PHP MySQLi extension. These functions are almost identical to their mysql equivalent, but come with numerous improvements.
Also, you would likely want to improve the validation of the $_POST['year'] field. Ensuring that it is an integer with is_int() wouldn't be a bad idea. You could also typecast it with (int) like (int) $year = mysql_real_escape_string($_POST['year']); and then perform the query if the year isn't 0. Perhaps you know all this already... or perhaps I'm getting ahead of myself. Either way, I'll stop. :)
You can find more info about Mysql select query syntax on
http://dev.mysql.com/doc/refman/5.1/en/select.html.
Also don't use # for errors suppression in php-code. Because of it will slow your script. Try to process such situation manually. In this case (#mysql_query($query)) it seems it doesn't make sense anyway.

Categories