Give unique value for submit button - php

In my table each and every row has a cell with a submit button.
Here is my code
<?php
# Init the MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("selfie") or die(mysql_error()) ;
# Prepare the SELECT Query
$selectSQL = 'SELECT * FROM `image_upload` INNER JOIN user_table
ON image_upload.user_id=user_table.user_id WHERE flag="0" ORDER BY timestamp DESC';
# Execute the SELECT Query
if( !( $selectRes = mysql_query( $selectSQL ) ) ){
echo 'Retrieval of data from Database Failed - #'.mysql_errno().': '.mysql_error();
}else{
?>
<table border="2">
<thead id="head">
<tr>
<th id="head">User name</th>
<th>Category</th>
<th>Description</th>
<th>Image</th>
<th>Location</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
if (isset($_GET['submit'])) {
$mobile = $_GET['dmobile'];
$query = mysql_query("update image_upload set
flag='$mobile' " );
}
if (isset($_GET['submit'])) {
header("Location: imageManagement.php");
}
if( mysql_num_rows( $selectRes )==0 ){
echo '<tr><td colspan="4">No Rows Returned</td></tr>';
}else{
while( $row = mysql_fetch_assoc( $selectRes ) ){
echo "<tr>
<td>{$row['user_name']}</td>
<td>{$row['category']}</td>
<td>{$row['description']}</td>
<td ><img src='uploads/".$row['image']."'width=300px height=200px></td>
<td>{$row['location']}</td>
<td><form class=\"form\" method=\"get\"><label></label><br/>
<input class=\"input\" type=\"text\" name=\"dmobile\" value=\" {$row['flag']}\" />
<br>
<input class=\"submit\" type=\"submit\" name=\"submit\" value=\"update\" />
</form></td>
</tr>\n";
}
}
?>
</tbody>
</table>
<?php
In here when do changes and click on submit button of one row each and every rows are updated. How can I give unique value for each and every submit button.

Comment to answer, since OP said it works.
OP: "It's work. Thank you very much.... :) – Lanka"
Add this to your form:
<input type=\"hidden\" name=\"the_id\" value=\"{$row['id']}\" />
then add:
$theid = $_POST['the_id'];
then,
$query = mysql_query("update image_upload set flag='$mobile'
WHERE id = '$theid' " );
You may need to play around with it a bit, in the hidden input that is.
This is based on having an "id" column of course.
N.B.:
You should validate the user input (even if it's a hidden field)
Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
As it stands, you are using a deprecated MySQL library, which leaves you open to SQL injection.

else{
$counter=0 ;
while( $row = mysql_fetch_assoc( $selectRes ) ){
$value="Update ".$counter ;
$counter++ ;
echo "<tr>
<td>{$row['user_name']}</td>
<td>{$row['category']}</td>
<td>{$row['description']}</td>
<td ><img src='uploads/".$row['image']."'width=300px height=200px></td>
<td>{$row['location']}</td>
<td><form class=\"form\" method=\"get\"><label></label><br/>
<input class=\"input\" type=\"text\" name=\"dmobile\" value=\" {$row['flag']}\" />
<br>
<input class=\"submit\" type=\"submit\" name=\"submit\" value=\"".$value."\" />
</form></td>
</tr>\n";
}
}
I do not think the question is clearly framed but by replacing the else part of your code with the above code you will get different values for submit button ie., update 0,update 1 and so on.. Hope this helps.

Related

Failing to update the new data entered by administrator

Look like everything is working fine with this code but in fact fails to update the database, Data are displayed correctly while fetching data but when i press update Button the data disappear but no update has been executed. It look fine to me but seems i am wrong.
This is a project for my professor so i don't care for the SQL injection and others.
<html>
<head>
<link rel="stylesheet" type="text/css" href="btnstyle.css">
<title>Managament System</title>
</head>
<body>
<h1>TU Chemnitz Student managament system</h1>
<br>
ADD Person
Edit Person
Manage Boards
Manage Departments
Search N&S
Triple Search
Membership
<br>
<br>
<?php
// set database server access variables:
$host = "localhost";
$user = "";
$pass = "";
$db = "";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$querys = "SELECT * FROM tblperson";
// execute query
$result = mysql_query($querys) or die ("Error in query: $query. ".mysql_error());
echo "<table border=1 align=center>
<tr>
<th>Personal ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Deparment</th>
<th>Board</th>
<th>Marticulation Number</th>
<th>Reg Date</th>
<th>Action</th>
</tr>";
while($row = mysql_fetch_array($result)) {
?>
<?php
echo '<tr>';
echo '<td>'. $row['personid'].'</td>';
echo '<td>'. $row['personname'].'</td>';
echo '<td>'. $row['personsurname'].'</td>';
echo '<td>'. $row['persondepartment'].'</td>';
echo '<td>'. $row['personboard'].'</td>';
echo '<td>'. $row['martinumber'].'</td>';
echo '<td>'. $row['personregdate'].'</td>';
echo '<td>'.' EDIT '.'</td>';
}
?>
</body>
</html>
and this is the edit file which seems to problematic.
<?php
include_once('coneksioni.php');
if(isset($_GET['edit']))
{
$personid = $_GET['edit'];
$res = mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row = mysql_fetch_array($res);
}
if(isset($_POST['newpersonname']))
{
$newpersonname = $_POST['newpersonname'];
$personid = $_POST['personid'];
$sql = "UPDATE tblperson SET personname = '$newpersonname' WHERE personid = '$personid'";
$res = mysql_query($sql) or die ("Cant be updated");
echo "< meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
<form action="edit20.php" method="POST">
<table border="0">
<tr>
<td>First Name</td>
<td><input type="text" name="newpersonname" value="<?php echo $row[1];?>" maxlength="30" size="13"></td>
</tr>
<tr>
<td>Last Name</td>
<td> <input type="text" name="personsurname" value="<?php echo $row[2];?>" maxlength="30" size="30"></td>
</tr>
<tr>
<td>Department</td>
<td>
<select name='persondepartment'>
<option>Production</option>
<option>Sales</option>
</select>
</td>
</tr>
<tr>
<td>Board</td>
<td>
<select name='personboard'>
<option>Evaluation</option>
<option>Executive</option>
<option>Research</option>
</select>
</td>
</tr>
<tr>
<td>Marticulation Number</td>
<td> <input type="text" name="martinumber" maxlength="60" size="30"></td>
</tr>
<tr>
<td>Date of Registration</td>
<td><input type="date" name="personregdate" maxlength="7" size="7"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value=" Update"></td>
</tr>
</table>
</form>
You are looking for personid when the Update button is pressed on the form in edit20.php but that value has never been set so it will be empty and the update will fail.
After
<form action="edit20.php" method="POST">
add:
<input type="hidden" name="personid" value="<?php echo $personid; ?>">
On edit page seem your confusing the same variable with different values. If you state $personid variable to contain the edit value from get, then just re-use the variable don't assign new value. On this line you assign new value :
$personid = $_POST['personid'];
Don't assign new value since it has the initial value already to use just set the variable global for usage
$personid = $_GET['edit'];
Or else create a hidden element and pass edit value into it.
Please add name attribute for your update button
<td colspan="2"><input type="submit" name="update" value=" Update"></td>
and chk whether the update button set or reset as in the place of
if(isset($_POST['newpersonname'])) // change text 'newpersonname' as 'update'
You use a variable that doesn't excist:
<?php
include_once('coneksioni.php');
if(isset($_GET['edit']))
{
$personid = $_GET['edit'];
$res = mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row = mysql_fetch_array($res);
}
if(isset($_POST['newpersonname']))
{
$newpersonname = $_POST['newpersonname'];
$personid = $_POST['personid']; // this doesn't excist
$sql = "UPDATE tblperson SET personname = '$newpersonname' WHERE personid = '$personid'";
$res = mysql_query($sql) or die ("Cant be updated");
echo "< meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
$personid = $_POST['personid']; doesn't excist in your code. Its simply a piece of code you put in there to probably proces, but forgot to define the variable in the code. Place the following in your form.
<input type="hidden" name="personid" value="<?php echo $_GET['edit']; ?>">
You only use this just once because you send the form back after proces to your home, hence it wont be used anymore. You can also use the avariable you defined as $personid; on that position.
If that fails, something maybe wrong in your query. Try to echo out the query (remove qucikly the meta command) by simply just do echo $sql after you do the sql query. 9 out of 10 times, it's a typo.

How do I pass multiple ID to jobCart page?

I've a job list page, displaying all jobs and there are checkbox next to each one, and there is an Add button at the bottom of the page, to add it to JobCart.php
I honestly don't know how to pass multiple record ID or single ID to jobCart.php
I want the when the user to click the button "Add" pass all selected ID to jobCart.php
please help me
<?php
// adding JobsLists.php to this page to interact witht it.
require ("../JobsLists.php");
//Connect to DB
//include_once("Project/CIEconn.php");
$mysqlCON= mysqli_connect("localhost", "root", "","CIE") or die(mysqli_connect_error());
mysqli_select_db($mysqlCON,'CIE') or die ("no database");
$ID = isset($_POST['Id']); // 1 2
if( isset($_POST['pick']) ){
if( empty($ID) || $ID == 0 ){
echo"<h4> please choose something to move to your job list </h4>";
}else{
// Code here ..
// here here ONLY for TEST to check if I can interact eith jobLists.php
addJob();
// to get all ID from each selected job
$impid = implode("' , '" , $_POST['Id']);
}
}
$sqlCommand = "SELECT * FROM Fiscal WHERE NoStudent > '0' ";
$result = mysqli_query($mysqlCON,$sqlCommand) or die(mysqli_error($mysqlCON));
echo '
<form action= "Fiscal.php" method = "post">
<table width ="100%" cellpadding ="4" border="1" >
<tr>
<th>Check </th>
<th>Jobs Name</th>
<th>Description</th>
<th> No Students needed</th>
<th>Due Date</th>
</tr>';
while ($row = mysqli_fetch_array($result) ){
// name = 'Id[]'
echo "<tr>
<td> <input type='checkbox' name='Id[]' value='". $row['Id'] ."' /> </td>
<td> ". $row['JobName'] ." </td>
<td> ". $row['Description'] ." </td>
<td> ". $row['NoStudent'] . "</td>
<td>". $row['DueDate'] ." </td>
</tr>";
}
echo '
</table>
<br/>
<div align="center">
<input type="submit" name="pick" value="Add Job" />
<input type="reset" value="Clear Marks" />
</div>
</form>
';
?>
<html>
<head><title> Fiscal </title></head>
<br>
<body>
</body>
</html>
First of all, start session at the very top of your page, like this:
<?php
session_start();
?>
And during the form processing store $_POST['Id'] array to $_SESSION superglobal and redirect the user to jobCart.php page using header() function.
And one more thing, $_POST['Id'] would be an array, so use count() function to see it's empty or not. So your code should be this:
// your code
if(isset($_POST['pick'])){
if(count($_POST['Id'])){
// store `$_POST['Id']` array to `$_SESSION` superglobal
$_SESSION['ids'] = $_POST['Id'];
// redirect the user to jobCart.php page
header("Location: jobCart.php");
exit();
}
}
// your code
And in jobCart.php you can do something like this:
$impid = implode("','" , $_SESSION['ids']);
// rest of your code

Update Multiple rows at one time in PHP

I am trying to update multiple rows on submit of a form (in particular this one is the "hours" field.
I have it working but only one of the value updates vs all of them.
There is the possibility of having different values for each update.
The form code:
$query2 = "select * FROM work_hours WHERE formid = $formid ";
$result = $mysqli->query( $query2 );
$num_results = $result->num_rows;
if( $num_results > 0){
echo " <table border='0' align='center'>
<tr>
<td colspan='2' align='center'>
<strong> Time Away Break Down</strong>
</td>
</tr>
<tr>
<td align='center'>Date</td>
<td align='left'>Hours</td>
</tr>";
while( $row = $result->fetch_assoc() ){
extract($row);
echo " <tr>
<td class='hidden_sm' align='center'>
<input type='text' name='id' size='10' value='$id' class='dept' readonly style='width:30px;'>
<input type='text' name='date' size='40' value='$date' class='dept' readonly> <input type='text' name='end_date' size='40' value='$end_date' class='dept' readonly>
</td>
<td class='hidden_sm' align='left' >
<input type='text' name='hours' size='10' style='width:30px;' value='$hours' class='dept' >
</td>
</tr>
";
}
echo "<tr>
<td colspan='2' align='center'>
<input type='submit' name='Submit' value='Submit Request'>
</td>
</tr>
</form>
</table>";//end table
Submit Code:
$id = $_POST['id'];
$formid = $_POST['formid'];
$hours = $_POST['hours'];
include 'connect-db.php';
$stmt = $mysqli->prepare("UPDATE work_hours SET hours = ? WHERE formid = ?");
$stmt->bind_param('si',
$_POST['hours'],
$_POST['formid']);
$stmt->execute();
if ( $stmt ) {
echo "<p align='center'>Thank you, this request has been approved.<BR>You will be redirected in 5 seconds</p>";
} else {
echo "Error, you status cannot be updated. <BR> Please contact your system administrator.";
}
$stmt->close();
?>
Could anyone point me in the right direction to have all values update on submit, as I have had zero luck.
As well I do understand the need to prevent SQL Injections, and that I am working, so no need to remind me.
Thanks in advance!
Looks like you'll want to use a CASE statement as explained here:
How does MySQL CASE work?
Use a loop to build the statement and you're better off using the id as the identifier instead of formid, since the id is the unique value and you could have different results in the form.

ANSWERED: Form is updating database correctly

This code now works to update each row of data individually if submit button is clicked.
Original issue was that I could not get each record updated individually and it was updating ALL rows instead of just the one matching the ID I wanted.
CONNECTIONS STUFF
<form method='post'>";
$query="SELECT * FROM table WHERE approved='no'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
echo "<p>$count pending approval.</p>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$id=$row['id'];
$name = $row['name'];
$extra = $row['extra'];
echo "
<table>
<tr>
<td>ID:</td>
<td>$id <input type='hidden' name='id[]' value='$id'></td>
</tr>
<tr>
<td>Name:</td>
<td>$name <input type='hidden' name='name[]' value='$name'></td>
</tr>
<tr>
<td>Extra:</td>
<td>$extra <input type='hidden' name='extra[]' value='$extra'></td>
</tr>
<tr colspan='2'>
<td>
<center><input name='submit' type='submit' value='Approve'></form></center>
</td>
</tr>
</table><br>
";}
if($_POST['submit']) {
$update = "UPDATE table SET approved='yes' WHERE id='$id' LIMIT 1";
if(mysql_query($update)) $count++;
else die("Error in query:<br>$sql<br>");
echo "<p><b>$name has been approved</b></p>";
}
?>
You have to move your update statement outside the while (($i < $num)) {...}.
Currently, that's inside the loop...
You are looping over each row, and then checking if the submit button was clicked, and if so updating the row.
The issue is that you dont identify which button was clicked and so each row is updated when any button is pressed. Try this:
if (isset($_POST['accepted']) && isset($_POST['id']) && $_POST['id'] == $id)
This will check to see if the submited form corresponds to the current row
The fault is in here:
...
<?php
if (isset($_POST['accepted'])) {
$query_update = "UPDATE mytable SET accepted='yes' WHERE id ='$id'";
$result_update=mysql_query($query_update);}
$i++;
}
mysql_close();
?>
....
$i is the run vairable to iterate over ALL rows. it only gets incremented when $_POST['accepted'] is set. And in this particular case, it's generateing an update for each and evry single row with an $id which has come from the databse instead of the current POST.
Thus: all records will be updated.
Modfify:
...
<?php
if (isset($_POST['accepted']) && isset($_POST['id']) ) {
$updateId = $_POST['id'];
$query_update = "UPDATE mytable SET accepted='yes' WHERE id ='$updateId '";
$result_update=mysql_query($query_update);
mysql_close();
}
$i++;
?>
....

Unknown column 'chenzhen' in where clause

I have a PHP script that connects to a MySQL database using the mysqli extension to search for Blog Posts based on Username or ID. I created a VIEW called BlogSearch that uses joins form other tables to aggregate the information I need together that is represented like this:
The Tables it pulls from are called Profiles that has the User information, BlogPosts and BlogCategory
Everytime I search I get the error:
Unknown column 'chenzhen' in 'where clause'
The PHP code I'm using below:
require 'database.php';
$query = "SELECT * FROM BlogSearch";
echo <<<EOF
<form method='post' action='' style="padding: 30px 0;">
<table cellspacing="0" border="0" style="float: left;">
<tr>
<td>Search Blog Posts by Username/ID</td>
<td><input type="text" id="search" name="search" style="width: 300px;"/></td>
<td><input type="submit" id="submit_button" value="Search" name="submit_button" style="float: right;" /></td>
</tr>
</table>
</form>
EOF;
if(isset($_POST['submit_button']))
{
$search_term = $_POST['search'];
$query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = $search_term ";
// run the query and store the results in the $result variable.
$result = $mysqli->query($query) or die(mysqli_error($mysqli));
}
if ($result) {
// create a new form and then put the results
// into a table.
echo "<form method='post' action='delete.php' style='clear: both;'>";
echo "<table cellspacing='0' cellpadding='15'>
<th width='5%'>
<input type='checkbox' id='allcb' onclick='checkAll(this)' name='allcb' />Check All
</th>
<th width='10%'>User</th>
<th width='85%'>Blog Post Title</th>
";
while ($row = $result->fetch_object()) {
$title = substr($row->PostCaption,0,50);
$id = $row->PostID;
$user = $row->NickName;
//put each record into a new table row with a checkbox
echo "<tr>
<td><input type='checkbox' name='checkbox[]' id='checkbox[]' value=$id />
<td>$user</td>
<td>$title</td>
</tr>";
}
// when the loop is complete, close off the list.
echo "</table><p><input id='delete' type='submit' class='button' name='delete' value='Delete Selected Items'/></p></form>";
}
I don't know why it's even identify the username as a column. Can anyone point me in the right direction to fix this?
Thanks in advance.
Any element in an SQL query that isn't an SQL keyword or a literal (denoted by single quotes), is assumed to be an object (e.g. table, column) name.
Your problem is the missing quotes around $search_term in your WHERE clause:
$query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = $search_term ";
You should add them, as thus:
$query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = '$search_term' ";
Enclose your $search_term in single quotes in where clause like this '$search_term'

Categories