What am I doing wrong? Edit table data in form [closed] - php

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a table with a edit link and a delete button on each row. Delete button is working fine but the edit link I don´t know what I´m doing wrong with!
Clicking the edit link for a specific row it leads to edit page with the form BUT the data is not filled out. There is no error message... I can see up in the URL field that it´s the correct id for the chosen movie.
What am I missing? Do I need to write any queries etc on the edit page as well? I did try and make it a require page so when clicking on the edit button the edit form pops up on the index page. But I couldn't manage to do that.
I know I'm using mysql functions which are outdated, and I have yet to add SQL protection.
The database is called moviedata and has 2 tables.
Table 1 is called: movies
Fields/columns (5): id (primary key, AI), ****title** , release_year,** ****genre_id**, **director****
Table 2 is called: categories
Fields/columns (2): genre_id (primary key, AI), genre
There is a relation (Foreign key) between genre_id (primary key, table 2) and genre_id (table 1).
index.php code
<!DOCTYPE html>
<html>
<head>
<title>My movie library</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="mall.css" />
</head>
<body>
<?php
require 'connect.inc.php';
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = $_POST['id'];
$query = "DELETE FROM movies WHERE id=".$id." LIMIT 1";
if (!mysql_query($query, $sql))
echo "DELETE failed: $query<br>".
mysql_error() . "<br><br>";
}
$query = "SELECT * FROM movies m INNER JOIN categories c ON m.genre_id = c.genre_id";
$result = mysql_query($query);
if (!$result) die ("Database access failed:" .mysql_error()) ;
$rows = mysql_num_rows($result);
echo '<table><tr><th>Title</th><th>Release year</th><th>Genre</th><th>Director</th><th>Update</th><th>Delete</th></tr>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr><td>' .$row["title"] . '</td>' ;
echo '<td>' .$row["release_year"] . '</td>' ;
echo '<td>' .$row["genre_id"] . '</td>' ;
echo '<td>' .$row["director"] . '</td>' ;
echo '<td>'."<a href='edit_movie.php?edit=" . $row["id"] . "'>Edit</a>".'</td>';
echo '<td><form action="index.php" method="POST">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="id" value="'. $row["id"] .'" />
<input type="submit" value="Delete" /></form>
</td></tr>' ;
}
echo '</table>';
?>
</body>
</html>
And here is the code on edit_movie.php page. The edit page with the form:
<!DOCTYPE html>
<html>
<head>
<title>My movie library</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="mall.css" />
</head>
<body>
<?php
require 'connect.inc.php';
//close MySQL
mysql_close($sql);
?>
<p>Edit movie</p>
<div id="form_column">
<form action="edit_movie.php" method="post">
<input type="hidden" name="id" value="<?php if (isset($row["id"])) ?>" /> <br>
Title:<br> <input type="text" name="title" value="<?php if (isset($row["title"])) { echo $row["title"];} ?>" /> <br>
Release Year:<br> <input type="text" name="release_year" value="<?php if (isset($row["release_year"])) { echo $row["release_year"];} ?>" /> <br>
Director:<br> <input type="text" name="director" value="<?php if (isset($row["director"])) { echo $row["director"];} ?>" /> <br><br>
Select genre:
<br>
<br> <input type="radio" name="genre_id" value="1" checked />Action<br>
<br> <input type="radio" name="genre_id" value="2" />Comedy<br>
<br> <input type="radio" name="genre_id" value="3" />Drama<br>
<br> <input type="radio" name="genre_id" value="4" />Horror<br>
<br> <input type="radio" name="genre_id" value="5" />Romance<br>
<br> <input type="radio" name="genre_id" value="6" />Thriller<br><br>
<input type="submit" />
</form>
</div>
</body>
</html>
The database connection is in a separate connect.inc.php file which is required at the top of these files. The code in the connect.inc.php file you can see below:
<?php
//connect to MySQL
$servername = "localhost";
$username = "root";
$password = "";
$sql = mysql_connect($servername,$username,$password);
mysql_connect($servername,$username,$password);
//select database
mysql_select_db("moviedata");
?>

Well, your code is kinda mess, because it's not even procedural. You're making problems for yourself. Really.
There are some things you must remember when developing an application using PHP:
Never print/echo html tags.
Try to avoid this as much as possible because this makes your code unmaintainable and unreadable. Use an alternate syntax instead.
That is, PHP should be used as a template engine itself, not "generate" the ones.
Separate responsibilities. Clearly and wisely
A functions which connect to a database should not be used in a presentation (in this case - HTML). You'd create one file which is responsible for database, another one which is responsible for data manipulation(such as DELETE, CREATE, UPDATE operations) and the like.
Don't forget about SQL injection & XSS
Never trust data you get from superglobals like $_GET, $_POST, $_COOKIE and $_REQUEST. At minimum, mysql_real_escape_string() should be used for each dynamic input you are going to deal with.
Generally speaking, XSS allows to execute any JavaScript code via aforementioned superglobals as well as injecting another html code within general markup. In order to prevent this, basically htmlentities() would be great enough here.
Wrap things into a function
So instead of doing this,
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = $_POST['id'];
$query = "DELETE FROM movies WHERE id=".$id." LIMIT 1";
You should re-write it like so:
function delete_movie_by_id($id){
return mysql_unbuffered_query(sprintf("DELETE FROM `movies` WHERE id='%s' LIMIT 1", mysql_real_escape_string($id)));
}
if ( isset($_POST['delete'], $_POST['id']) ){
delete_movie_by_id($_POST['id']); // it's safe & readable now
}
Learn about OOP and switch to PDO
Well, a procedural code is not the way to go when you're developing something like this. Next time you will be writing something, you'd really start using both PDO for database access and OOP.
I could go on, but it's better to stop now, and switch back to your original question.
Well, you didn't say which error exactly you get. For example, do you know if mysql_select() returns FALSE ( === failure on database selection), this won't terminate the script!? According to code you've posted, you do not "track it" in any way.
First
So, connect.inc.php should look like this:
error_reporting(E_ALL); // <-- Important!
$servername = "localhost";
$username = "root";
$password = "";
if ( ! mysql_connect($servername,$username,$password) ){
die(sprintf('Cannot connect to MySQL server because of "%s"', mysql_error()));
}
//select database
if ( ! mysql_select_db("moviedata") ){
die(sprintf('Cannot select a database, because of "%s"', mysql_error()))
}
Second
In edit_movie.php page, this code block, isn't required at all. The connection will be closed automatically when a script terminates.
So just remove this:
<?php
require 'connect.inc.php';
//close MySQL
mysql_close($sql);
Third
In that edit_movie.php, you're clearly asking: if ( isset($row['some_column']) )..., but what is it all about? Where's the $row itself? it wasn't defined anywhere, so you won't get what you expect. Here:
<input type="hidden" name="id" value="<?php if (isset($row["id"])) ?>" /> <br>
Title:<br> <input type="text" name="title" value="<?php if (isset($row["title"])) { echo $row["title"];} ?>" /> <br>
Release Year:<br> <input type="text" name="release_year" value="<?php if (isset($row["release_year"])) { echo $row["release_year"];} ?>" /> <br>
Director:<br> <input type="text" name="director" value="<?php if (isset($row["director"])) { echo $row["director"];} ?>" /> <br><br>
Okay, that's enough.
Consider, rewriting your application like this:
File: movie.inc.php
require_once('connect.inc.php');
/**
* Fetch all movies from a table
* #return array on success, FALSE on failure
*/
function get_all_movies(){
$query = "SELECT * FROM movies m INNER JOIN categories c ON m.genre_id = c.genre_id";
$result = mysql_query($query);
if ( ! $result ){
return false;
} else {
$return = array();
while ($row = mysql_fetch_assoc($result)){
$return[] = array('director' => $row['director'], 'genre_id' => $row['genre_id'], 'release_year' => $row['release_year'], 'title' => $row['title'], 'id' => $row['id']);
}
return $return;
}
}
function delete_movie_by_id($id){
// I already wrote this, see above
}
File index.php
<?php
require('movie.inc.php');
if ( isset($_GET['delete']) && isset($_GET['id']) ){
if ( delete_movie_by_id($_POST['id']) ){ //it's 100% safe
die('Movie has been removed. Refresh the page now'); // or the like
} else {
// could not - handle here
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>My movie library</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="mall.css" />
</head>
<body>
<table>
<tr>
<th>Title</th>
<th>Release year</th>
<th>Genre</th><th>Director</th>
<th>Update</th>
<th>Delete</th>
</tr>
<?php foreach (get_all_movies() as $index => $row) : ?>
<tr>
<td><?php echo $row['title'];?></td>
<td><?php echo $row['release_year']; ?></td>
<td><?php echo $row['genre_id'];?></td>
<td><?php echo $row['director'];?></td>
<td><a href='<?php printf('edit_movie.php?edit=%s', $row['id']);?>>Edit</a></td>
<td>
<form action="index.php" method="GET">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="id" value="<?php echo $row['id'];?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
I'm tired now, hope you can get the core idea from this answer.
UPDATE
There are basic steps to make a movie "editable" :
1) You grab the data you are going to edit (from the table)
2) You send edited data back to the server (php script)
3) You validate the input
4) You run UPDATE query
That's all.
So it would be similar to this (File: edit_movie.php):
<?php
require_once('movie.inc.php');
/**
* Grabs the movie data by its id
*
* #param $id A movie id
* #return array on succes, FALSE if $id is wrong
*/
function get_movie_by_id($id){
$query = sprintf("SELECT * FROM `enter_movie_table_name_here` WHERE `id` = '%s' LIMIT 1", mysql_real_escape_string($id));
$result = mysql_query($query);
if ( ! $result ){
return false;
} else {
return $result;
}
}
function update_movie_by_id($id, array $data){
$query = sprintf("UPDATE `the_movie_table`
SET `director` ='%s',
`genre_id` = '%s',
`relase_year` ='%s',
`title` = '%s' WHERE `id` = '%s' LIMIT 1"),
mysql_real_escape_string($data['director']),
mysql_real_escape_string($data['genre_id']),
mysql_real_escape_string($data['relase_year']),
mysql_real_escape_string($data['title']),
mysql_real_escape_string($id) );
// not mysql_query() !!! but this
return mysql_unbuffered_query($query);
}
// Next thing is to get an id by query string,
// So if it was /movide_edit.php?id=1
// then id we have is 1
// So we need to handle that right now
if ( isset($_GET['id']) ){
$movie = get_movie_by_id($_GET['id']);
if ( ! $movie ){ // <- make sure that id isn't fake
die(sprintf('Invalid movie id "%s"', $_GET['id']));
}
} else {
die('Please supply an id you want to edit'); // <- this makes sence
}
// Ok, we'll reserve this block for an update
if ( !empty($_POST) ){ // This will run when user clicked on Save button
if ( update_movie_by_id($_POST['id'], array(
'director' => $_POST['director'],
'genre_id' => $_POST['genre_id'],
'relase_year' => $_POST['relase_year'],
'title' => $_POST['title']
)) ){
die('Movie has been updated');
} else {
die('Could not update a movie for some wicked reason..');
}
}
// That's all. Now it can:
//1) Fetch the data
//2) Edit accordingly
?>
<!DOCTYPE html>
<html>
<!--
This is kinda quick and dirty form
You need to fix this later
-->
<body>
<form method="POST">
<label for="title">Title</label>
<input type="text" name="title" value="<?php echo $movie['title']; " />
<!--
Add another elements this way..
-->
<button type="submit">Save</button>
</form>
</body>
</html>

Related

PDO MySQL Update not working correctly on edit page

A 'quiz' currently contains a quiz id, name, description and topic (from a topic table).
I am wanting to setup a simple 'Edit Quiz' page.
The problem is - if a quiz is called 'Quiz1' and I change the quiz name on the edit page to 'Quiz2', once the save button is clicked it will revert back to 'Quiz1' and not stored.
I have setup an echo as shown in the code to check that they are actually getting stored, after the save button is clicked it would show 'Quiz1' but this value is not stored in my database. The SQL Has been tested on PhpMyAdmin and seems to work too.
PHP Code:
<? if (!empty($_POST)) {
$id = $_POST['qzid'];
$qzname = $_POST['qzname'];
$qzdesc = $_POST['qzdesc'];
$ctname = $_POST['ctname'];
$checkQuiz = $db->prepare("SELECT qz_name FROM quizzes WHERE qz_name = :qz_name");
$checkQuiz->execute(array(':qz_name' => $qzname));
$qzChanged = "Quiz details updated successfully";
$sql = "UPDATE quizzes SET `qz_name` = :qzname, `qz_desc` = :qzdesc WHERE `quizzes`.`id` = :qzid";
$q = $db->prepare($sql);
$q->execute(array(':qzname' => $qzname, ':qzdesc' => $qzdesc, ':qzid' => $id));
echo $qzname, $qzdesc; //THIS RETURNS THE CHANGED VALUES
}?>
HTML Code:
<form action="edit_quiz.php?id=<?php echo $row['id'] ?>" method="POST">
<input type="hidden" name="qzid" id="qzid" value=""/>
<!-- selection box -->
<p>Topic Name:
<select class="form-control" name="ctname" id="ctname">
<?php
while ($tresult = $stmt->fetch()) {
echo "<option>" . $tresult["ct_name"] . "</option>";
}
?>
</select>
</p>
<p>Quiz Name: <input type="text" name="qzname" value="<?php echo $row['qz_name']; ?>"/></p>
<p>Quiz Description: <textarea name="qzdesc" value=""/><?php echo $row['qz_desc']; ?> </textarea></p>
<input type="submit" class="btn btn-success" value="Save"/> <a class="btn" href="quizzes.php">Back</a>
Please note this code has been simplified.
Any help I would appreciate very much thanks!
You are not posting the id it looks like.
Is your database named localhost, otherwise remove that part.

checkbox value to mysql/php

im triyng to figure out a problem for days and have some progress but im stuck with some checkbox page.
So the "project" is some kind of "online car stand" and im stuck in the insert car part.
I got the html and php for insert a car into the sql table.
Then after the car i have a link to insert extras of the car, like abs,cruise control, gps ...etc...
The Html is something like this:
<?php
include "verifica.php";
?>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title> Stand Automovel
</title>
</head>
<body>
<form action="extras.php" method="POST">
<P class="style2"style2"> Extras:
<div class="style2">
<input type="checkbox" name="chk" value="1">GPS<br>
<input type="checkbox" name="chk" value="2">ABS<br>
<input type="checkbox" name="chk" value="3">Computador De Bordo<br>
<input type="checkbox" name="chk" value="4">Ar Condicionado<br>
</div>
<P> </P>
<P><INPUT TYPE=submit VALUE="Submeter"> <INPUT TYPE=reset VALUE="Limpar"> </P>
<P> </P>
</form>
</body>
The php page code is this one:
<html>
<head>
<meta charset="UTF-8">
<title>Inserir Automoveis</title>
</head>
<body>
<?php
include "connect.php";
$sql = "INSERT INTO extra (extra.id_carro,extra.id_lista_extra) SELECT carro.id_extras , ? FROM carro,lista_extra,extra ORDER BY carro.id_carro DESC LIMIT 1";
if($teste= $mysqli->prepare($sql)) {
$teste->bind_param("s",$_REQUEST["extra.id_lista_extra"]);
$teste->execute();
if ($teste>affected_rows == -1) {
echo $print;
echo "<p>". $mysqli->error. "</p>";
}
else {
echo "<sp>Carro inserido com sucesso!</p>";
}
}
?>
The goal with that $sql is to get the last id from last car inserted on row cars and add 1 extra to him passed by the check box.
i have tried just with 1 box because i read that if a checkbox was unchecked pass "null"argument.
I tried already with diferent aproaches. My final goal is create a for cicle that creates the number of rows in table extra for each number of extra checked in my checkbox.
(i tried something like this but with no sucess)
$checkbox1 = $_POST['chk'];
if($_POST["Submit"]=="Submit"){
for ($i=0;$i<sizeof ($checkbox1)$i++){
$sql = "INSERT INTO extra (id_lista_extra) values('".$checkbox1[$i]."')";
mysql_query($sql) or die(mysql_error());
}
}
i got some php errors on that $i .
If someone can give me a hint i would appreciate.
Thanks
Here is an example all you would have to do is change the names inside these $_POST variables as well as change your HTML checkbox names to have a [] after them. e.g
<input type="checkbox" name="chk[]" value="1">GPS<br>
<input type="checkbox" name="chk[]" value="2">ABS<br>
$cat_array = array();
if(isset($_POST['chk'])){
if(is_array($_POST['chk'])) {
foreach($_POST['chk'] as $value){
array_push($cat_array, $value);
}
}else{
$value = $_POST['chk'];
array_push($cat_array, $value);
}
}
Now all these values are in an ARRAY. Do as you please with them, loop through them, call them by there indexes, etc..

+/- equation with a single textfield

I am making a very simple storage system, and i want to make it so that the user puts a number in the box, and press the + or - button, to add or subtract.
I don't know if it's even possible to do it, as simple as i wanted it to be :)
but anyway, here is the code so far for index.php
<?php $v_stk = "v_stk" ?>
<form action="index_sql.php" method="POST">
<input name="v_id" type="hidden" value="<?php echo $v_assoc["v_id"] ?>" />
<input name="v_stk" type="textfield" size="8" />
<input name="+" type="submit" value="+" style="height:23px; width:35px;" />
<input name="-" type="submit" value="-" style="height:23px; width:35px;" />
</form>
<td class="width50 sidepadding">
<?php echo $v_assoc["v_stk"]; ?></td>
<?php }; ?>
and here is for index_sql.php
<?php
require("db/db.php");
$v_id = mysql_real_escape_string($_POST["v_id"]);
$v_stk = mysql_real_escape_string($_POST["v_stk"]);
$sql = mysql_query("SELECT v_stk FROM vare WHERE v_id = '$v_id'");
$assoc = mysql_fetch_assoc($sql);
$v_nu = $v_stk + $assoc;
mysql_query("UPDATE vare SET v_nu = '$v_stk' WHERE v_id = '$v_id'");
header("location: index.php");
?>
I don't know if it is remotely close to something that would work, but with this code it gives me:
Fatal error: Unsupported operand types in C:\wamp\www\lager\index_sql.php on line 8
Because, You are performing addition with an array type variable.
$assoc = mysql_fetch_assoc($sql);
Here, $assoc is an array variable so try like this,
$v_nu = $v_stk + $assoc['v_stk'];

populating text fields from the sql using dropdown list Jquery

Hello there first time doing this, Basically I am rather confused on how to Re-populate text boxes from the database.
My current issue is that basically I have two tables in my database 'USER' and 'STATISTICS'.
Currently what is working is that my code is looking up the values of 'User_ID' in the 'USER' table and populating the values in the drop down list.
What I want from there is for the text fields to populate corresponding to those values from the database looking up the 'User_ID' E.G 'goal_scored' , 'assist', 'clean_sheets' and etc.
I am pretty baffled I have looked up on various different questions but cannot find what im looking for.
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("f_club",$link);
$sql = "SELECT * FROM user ";
$aResult = mysql_query($sql);
?>
<html>
<body>
<title>forms</title>
<link rel="stylesheet" type="text/css" href="css/global.css" />
</head>
<body>
<div id="container">
<form action="update.php" method="post">
<h1>Enter User Details</h1>
<h2>
<p> <label for="User_ID"> User ID: </label> <select id="User_ID" id="User_ID" name="User_ID" >
<br> <option value="">Select</option></br>
<?php
$sid1 = $_REQUEST['User_ID'];
while($rows=mysql_fetch_array($aResult,MYSQL_ASSOC))
{
$User_ID = $rows['User_ID'];
if($sid1 == $id)
{
$chkselect = 'selected';
}
else
{
$chkselect ='';
}
?>
<option value="<?php echo $id;?>"<?php echo $chkselect;?>>
<?php echo $User_ID;?></option>
<?php }
?>
I had to put this in because everytime I have text field under the User_ID it goes next to it and cuts it off :S
<p><label for="null"> null: </label><input type="text" name="null" /></p>
<p><label for="goal_scored">Goal Scored: </label><input type="text" name="Goal_Scored" /></p>
<p><label for="assist">assist: </label><input type="text" name="assist" /></p>
<p><label for="clean_sheets">clean sheets: </label><input type="text" name="clean_sheets" /></p>
<p><label for="yellow_card">yellow card: </label><input type="text" name="yellow_card" /></p>
<p><label for="red_card">red card: </label><input type="text" name="red_card" /></p>
<p><input type="submit" name="submit" value="Update" /></p></h2>
</form>
</div>
</body>
</html>
If anyone can help with understanding how to get to the next stage would be much appreciated thanks x
Rather than spending time on something complicated like AJAX, I'd recommend going the simple route of pages with queries, such as user.php?id=1.
Craft a user.php file (like yours) and if id is set (if isset($_GET['id'])) select that user from the database (after having sanitised your input, of course) with select * from users where id = $id (I of course assume you have an id for each user).
You can still have the <select>, but remember to close it with </select>. You might end up with something like this:
<form method="get">
<label for="user">Select user:</label>
<select name="id" id="user">
<option value="1">User 1</option>
...
</select>
<submit name="submit" value="Select user" />
</form>
This will send ?id=<id> to the current page and you can then fill in your form. If you further want to edit that data, create a new form with the data filled in with code like <input type="text" name="goal_scored" value="<?php echo $result['goal_scored']; ?>" /> then make sure the method="post" and listen on isset($_POST['submit']) and update your database.
An example:
<?php
// init
// Use mysqli_ instead, mysql_ is deprecated
$result = mysqli_query($link, "SELECT id, name FROM users");
// Create our select
while ( $row = mysqli_fetch_array($link, $result, MYSQL_ASSOC) ) {?>
<option value="<?php echo $result['id']; ?>"><?php echo $result['name'] ?></option>
<?php}
// More code ommitted
if (isset($_GET['id'])) {
$id = sanitise($_GET['id']); // I recommend creating a function for this,
// but if only you are going to use it, maybe
// don't bother.
$result = mysqli_query($link, "SELECT * FROM users WHERE id = $id");
// now create our form.
if (isset($_POST['submit'])) {
// data to be updated
$data = sanitise($_POST['data']);
// ...
mysqli_query($link, "UPDATE users SET data = $data, ... WHERE id = $id");
// To avoid the 'refresh to send data thing', you might want to do a
// location header trick
header('Location: user.php?id='.$id);
}
}
Remember, this is just an example of the idea I'm talking about, lots of code have been omitted. I don't usually like writing actually HTML outside <?php ?> tags, but it can work, I guess. Especially for smaller things.

PHP - How to submit a form containing input fields that point to different MySQL rows

I am setting up a form using this PHP that loops through all records a user may have:
<?php foreach ($items as $row): ?>
<tr>
<td>
<?php echo form_hidden('id', $row->id); ?>
</td>
<td>
<?php echo '<strong>' . $row->name . '</strong>'; ?>
</td>
<td>
<?php echo form_input('number', $number); ?>
</td>
<td>
<?php echo form_input('registry', $registry); ?>
</td>
<td>
<?php echo form_checkbox('OK', $ok, $ok); ?>
</td>
</tr>
<?php endforeach; ?>
This gives me a form with the following look:
The idea here is that each row belongs to a unique ID/row in the database, and I would like to allow the user to edit all on the same page/form, using a single submit button.
What would be the best way of implementing this?
When this data is submitted, there should be a way of looping through each packet of information (from each user) in my controller. Would this be done via ajax/json?
This does not use codeigntier, but you should be familiar with the general technique before attempting to use CI to shortcut this process. Codeigniter will help you with rendering the form elements, performing validation, escaping your input and performing your query - but it will only help you (do anything) if you understand the basic principles involved. Hope this helps
MARKUP
<form action="/process.php">
<div>
<h2>GORDON</h2>
<input type="text" name="user[1][number]" /> <!-- The number corresponds to the row id -->
<input type="text" name="user[1][registry]" />
<input type="checkbox" name="user[1][ok]" value="1" />
</div>
<div>
<h2>ANDY</h2>
<input type="text" name="user[242][number]" />
<input type="text" name="user[242][registry]" />
<input type="checkbox" name="user[242][ok]" value="1" />
</div>
<div>
<h2>STEWART</h2>
<input type="text" name="user[11][number]" />
<input type="text" name="user[11][registry]" />
<input type="checkbox" name="user[11][ok]" value="1" />
</div>
<input type="submit" />
PHP
$users = $_REQUEST['user'];
foreach ($users as $rowId => $info){
// YOU SHOULD MAKE SURE TO CLEAN YOUR INPUT - THIS IS A GUESS AT WHAT YOUR DATA TYPES MIGHT BE
$id = (int) $rowId;
$number = (int) $info['number'];
$registry = mysql_real_escape_string($info['registry']);
$ok = (int) ($info['ok']);
$q = "UPDATE user SET number = $number, registry = '$registry', ok = $ok WHERE id = $id";
mysql_query($q);
// You may want to check that the above query was sucessful and log any errors etc.
}
There's no need to use ajax mate.
For each put a hidden input with the ID of the row in this format:
<input type="hidden" name="id[<?= $row->id ?>]" value="<?= $row->id ?>" ?>
Do the same for each element in the tr, i.e. name them as
name="number[<?= $row->$id ?>]"
name="registry[<?=$row->$id ?>]"
name="ok[<?=$row->$id ?>]"
and once you post the FORM you can iterate each row with:
foreach ($_POST['id'] as $key => $value) {
echo $_POST['name'][$key];
}
You need to set up input-names as array-names, so you will send the whole form and may iterate over the entries.
e.g.
<?php
echo form_input('userdata[' . $row->id . '][number]', $number);
?>
which would possibly create an
<input name="userdata[1][number]" />
(I don't know where those form-functions came from…)
This will result in an array $_POST['userdata'] which may be iterated via:
foreach($_POST['userdata'] as $userId => $userInputFields)
{
$user = new User($userId);
$user->number = $userInputFields['number'];
// …
}

Categories