I have several forms, with different fields and purposes.
So i tought "hey, i'll build a generic insert.php page to input data to my database".
Ok, so far so good.
But now i need to link files to each record, so my form has a <input type="file"> field.
What i really want to do is to allow the user to select several files (pictures, videos), create a directory named like the table plus the id of the record that is being inserted (upload/$tablename/$id/), store the files and add the path to the database.
Something like:
ID | NAME | WEBPAGE | FILES
01 | john | john.com | /upload/tblWebpages/01/
02 | mike | mike.net | /upload/tblWebpages/02/
19 | jimy | jimy.org | /upload/tblWebpages/19/
Because i don't know how many files will be inserted or their names, and later i intend to fetch all images in that directory and display it.
Is it possible to know the record ID from the table at the time the upload is being processed?
Because, as explained above, i'd like to store the files under a directory called $ID.
How should i add it to my query?
Alright, to the code:
insert.php
include('classes/class.upload.php');
$server = "localhost";
$user = "root";
$password = "xxxxx";
$database = "myDB";
$tabela = $_POST['tabela'];
$diretorio = "upload/".$tabela."/";
mysql_connect($server,$user,$password);
mysql_select_db($database) or die("Unable to select database" . mysql_error());
// create an array to hold your filnames
$images = array();
$files = array();
foreach ($_FILES['imagem'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$handle = new Upload($file);
if ($handle->uploaded) {
$handle->Process($diretorio);
if ($handle->processed) {
echo 'OK ';
// add the filename to the array
$images[] = $handle->file_dst_pathname;
}
else { echo 'Upload error: ' . $handle->error; }
}
else { echo 'Upload error: ' . $handle->error; }
unset($handle);
}
foreach ($_POST as $field => $value) {
if (!preg_match("/$value/i", $tabela)) {
if (preg_match("/$field/i", 'data')) {$value = date('Y-m-d', strtotime($value));}
else {$value = mysql_real_escape_string($value);}
$campo .= $field . ',';
$valor .= '\'' . $value . '\'' . ',';
$query = "INSERT INTO $tabela ($campo) VALUES ($valor)";
$query = str_replace(",)",")",$query);
//echo " inside foreach RESULT = $result and QUERY = $query <br>";
}
}
$result = mysql_query($query);
echo " outside foreach RESULT = $result and QUERY = $query <br>";
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_close();
form.php (simplified)
<form method="POST" action="insert.php" class="classeform" enctype="multipart/form-data">
<label for="namee" class="lbl-d-input">Name: </label>
<input type="text" name="namee" id="namee" class="field">
<label for="webpage" class="lbl-d-input">Webpage: </label>
<input type="text" name="webpage" id="webpage" class="field">
<label for="files" class="lbl-d-input">Files: </label>
<input type="file" name="files[]" id="files" class="field-img">
<input type="hidden" name="tabela" value="mytbl">
<input type="submit" value="Enviar" class="btn-enviar">
</form>
Got it to work with mysql_insert_id()
Do you see your echo'd values?
I would start by writing out some debug code
For example:
After this line of code
if (!preg_match("/$value/i", $tabela)) {
I would put
print("Value Matched");
That way you know your getting into your for loop. Also I noticed your not appending to your $query variable inside the loop so the db entry is never being added?
Related
I am trying to write a code on PHP that will allow me to upload some specific columns from a CSV file to MySql table. I'm very new on PHP. Tried to watch some of tutorials, but they were not much helpful as they are only showing the examples on very little CSV files such as 2 rows and 2 columns... I am talking about approx 100 cols and hundreds of rows. I only need the information from some specific columns to add my table. Here's my code so far.. It gives Undefined offset error. I am open to new ideas.
$connection = mysqli_connect('localhost', 'root', 'MyPass', 'database') or die('connection failed');
if(isset($_POST['upload'])){
$fname = $_FILES['sel_file']['name'];
echo 'upload file name: '.$fname.' ';
$chk_ext = explode(".",$fname);
if(strtolower(end($chk_ext)) == "csv")
{
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 10, ",")) !== FALSE)
{
$sql = "INSERT into turbolister(site,format,currency) values('$data[0]','$data[1]','$data[2]')";
mysqli_query($connection, $sql) or die(mysqli_error($connection));
}
fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
} `
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
Import File: <input class="btn btn-primary" type="file" name='sel_file' size='20'> <br>
<input class="btn btn-primary" type="submit" name="upload" value='upload'>
</form>
For such a project I would recommend you another way of doing this.
For me there are some open questions:
Is it correct, that one line in csv is one line in database?
Is there a header-line in csv containing the column-names so that the order of the columns can change?
I've overworked your script a little bit - what you need to do is to adjust the behavior to your needs and also change the separation item for header-columns and normal-lines.
<?php
// Just for development purpose
error_reporting(E_ALL);
ini_set('display_errors', 1);
try {
// Try to connect to mysql-server with pdo instated of using mysqli
$dbCon = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'root', 'MyPass');
} catch (PDOException $e) {
// Catching error && stoping script
die('<strong>Error:</strong> Connection failed with error "' . $e->getMessage() . '"');
}
if(isset($_POST['upload'])) {
$filename = $_FILES['sel_file']['name'];
// Show filename of uploaded file
echo 'Uploaded file: ' . $filename . '<br>';
// Check file-extension for csv
// #ToDo: Determinate which mime-type your csv-files generally have and check for mime-type additionally or instated
if (pathinfo($filename, PATHINFO_EXTENSION) == 'csv') {
// Get file-content
$fileContent = file_get_contents($_FILES['sel_file']['tmp_name']);
// Split file into lines
$rows = explode("\n", $fileContent);
// Check for data
if (empty($rows) || count($rows) < 2) {
// Shwo error-messages && stopping script
die('<strong>Error:</strong> CSV-File does not contain data!');
}
// Get columns of header-row
$header = explode('|', $rows[0]);
// Set query variables
$query = 'INSERT INTO test (';
$values = '(';
// Build query based on header-columns
for($a = 0; $a < count($header); ++$a) {
// Add column
$query .= $header[$a] . ', ';
$values .= ':column' . $a . ', ';
}
// Finish query
$query = substr($query, 0, -2) . ') VALUES ' . substr($values, 0, -2) . ')';
// Loop through rows, starting after header-row
for ($b = 1; $b < count($rows); ++$b) {
// Split row
$row = explode(',', $rows[$b]);
// Check that row has the same amount of columns like header
if (count($header) != count($row)) {
// Show message
echo '<strong>Warning:</strong> Skipped line #' . $b . ' because of missing columns!';
// Skip line
continue;
}
// Create statement
$statement = $dbCon->prepare($query);
// Loop through columns
for ($c = 0; $c < count($row); ++$c) {
// Bind values from column to statement
$statement->bindValue(':column' . $c, $row[$c]);
}
// Execute statement
$result = $statement->execute();
// Check for error
if ($result === false) {
// Show info
echo '<strong>Warning:</strong>: DB-Driver returned error on inserting line #' . $b;
}
}
// #ToDo: Get numbers of row before import, check number of rows after import against number of rows in file
// Show success message
echo '<span style="color: green; font-weight: bold;">Import successfully!</span>';
} else {
die('<strong>Error:</strong> The file-extension of uploaded file is wrong! Needs to be ".csv".');
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
Import File: <input class="btn btn-primary" type="file" name='sel_file' size='20'> <br>
<input class="btn btn-primary" type="submit" name="upload" value='upload'>
</form>
I'm currently working on a bit of PHP and I've 3 text inputs. The values are searched in the MySQL database and should return whatever amount of results correspond with the entered criteria.
here is the search form:
<form id='SearchPersonal' method='post' action='businessUsersSearch.php' accept-charset='UTF-8'>
<fieldset >
<legend>Search</legend>
<div class='container'>
<label for='C_Name' >Business Name: </label><br/>
<input type='text' name='C_Name' id='C_Name' maxlength="50" /><br/>
<label for='C_County' >City: </label><br/>
<input type='text' name='C_County' id='C_County' maxlength="50" /><br/>
<label for='Job_Type' >Job Type: </label><br/>
<input type='text' name='Job_Type' id='Job_Type' maxlength="50" /><br/>
</div>
<div class='container'>
<input type='submit' name='Submit' value='Search' />
</div>
</fieldset>
</form>
Here is the PHP script it links too in the action:
<?php
$mysqli_link = mysqli_connect("server", "database", "pass", "user");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('C_Name', 'C_County', 'Job_Type');
$conditions = array();
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && $_POST[$field] != '') {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "'$field' LIKE '%" . mysqli_real_escape_string($mysqli_link, $_POST[$field]) . "%'";
}
}
// builds the query
$query = "SELECT C_Name, C_StreetNumber, C_StreetName, C_Postcode, C_County, C_Tele, C_Website, Contact_Forename, Contact_Surname, Contact_Email, Jobs.Job_Type, Jobs.Job_Price FROM Company INNER JOIN Jobs ON Company.Company_ID = Jobs.Company_ID";
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= " WHERE " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
$result = mysqli_query($mysqli_link, $query) or die(mysql_error());
mysqli_close($mysqli_link);
if(isset($_POST['submit'])) {
while($row = mysqli_fetch_assoc($result)) {
$C_Name = $row['C_Name'];
$C_StreetNumber = $row['C_StreetNumber'];
$C_StreetName = $row['C_StreetName'];
$C_Postcode = $row['C_Postcode'];
$C_County = $row['C_County'];
$C_Tele = $row['C_Tele'];
$C_Website = $row['C_Website'];
$Contact_Forename = $row['Contact_Forename'];
$Contact_Surname = $row['Contact_Surname'];
$Contact_Email = $row['Contact_Email'];
$Job_Type = $row['Job_Type'];
$Job_Price = $row['Job_Price'];
echo "<b>Name: $C_Name</b><br>Street Number: $C_StreetNumber<br>Street Name: $C_StreetName<br>Postcode: $C_Postcode<br>County: $C_County<br>Telephone: $C_Tele<br>Website: $C_Website<br>Contact Name: $Contact_Forename $Contact_Surname<br>Email: $Contact_Email<br>Job Type: $Job_Type<br>Job Price: $Job_Price<hr><br>";
}
}
}
?>
For some reason it is returning that there is "
unexpected end of file
" however I've checked the code and all the codes is closed off correctly (from what I can see) when I add another '}' in at the end the script doesn't return anything at all. Anyone know why this would be happening?
Source:
Search MySQL Database with Multiple Fields in a Form
Because you forget to close
if(isset($_POST['submit'])) {// you not close the condition
At the end of your file
Just add } at end of your file
Fixed:
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('C_Name', 'C_City', 'Job_Type', 'Review_Rate');
$conditions = array();
}
// builds the query
$query = "SELECT Company.C_Name, Company.C_StreetNumber, C_StreetName, C_Postcode, C_City, C_County, C_Tele, C_Website, Contact_Forename, Contact_Surname, Contact_Email, Job_Type, Job_Price, Review_Rate, Review_Comment
FROM Company
INNER JOIN Jobs ON Company.Company_ID = Jobs.Company_ID
INNER JOIN Review ON Jobs.Job_ID = Review.Job_ID";
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && !empty($_POST[$field])) {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "$field LIKE '%" . mysqli_real_escape_string($mysqli_link, $_POST[$field]) . "%'";
}
}
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= " WHERE " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
echo "$query";
$result = mysqli_query($mysqli_link, $query);
mysqli_close($mysqli_link);
if(isset($_POST['submit'])) {
while($row = mysqli_fetch_array($result)) {
$C_Name = $row['C_Name'];
$C_StreetNumber = $row['C_StreetNumber'];
$C_StreetName = $row['C_StreetName'];
$C_Postcode = $row['C_Postcode'];
$C_City = $row['C_City'];
$C_County = $row['C_County'];
$C_Tele = $row['C_Tele'];
$C_Website = $row['C_Website'];
$Contact_Forename = $row['Contact_Forename'];
$Contact_Surname = $row['Contact_Surname'];
$Contact_Email = $row['Contact_Email'];
$Job_Type = $row['Job_Type'];
$Job_Price = $row['Job_Price'];
$Rating = $row['Review_Rate'];
$Comment = $row['Review_Comment'];
echo "<b>Name: $C_Name</b><br>Street Number: $C_StreetNumber<br>Street Name: $C_StreetName<br>City: $C_City<br>Postcode: $C_Postcode<br>County: $C_County<br>Telephone: $C_Tele<br>Website: $C_Website<br>Contact Name: $Contact_Forename $Contact_Surname<br>Email: $Contact_Email<br>Job Type: $Job_Type<br>Job Price: $Job_Price<br>Rating: $Rating<br>Comment: $Comment<hr><br>";
}
}
?>
I have the facility to update what I call 'documents' (ver similar to creating a post) on my cms which works fine but I have introduced categories where the documents are associated to them. Now I have managed to bind them when creating the doc from new but when trying update them I am getting a bit stuck. I am using checkboxes to show the list of categories and when selected it updates a join table which uses the doc_id and the cat_id.
Here is the script for updating the doc:
<?php
include ('includes/header.php');
require ('../../db_con.php');
echo '<h1>Document Edit</h1>';
// Check for a valid document ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_docs.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
exit();
}
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
// Check for a document name:
if (empty($_POST['doc_name'])) {
$errors[] = 'You forgot to enter your document name.';
} else {
$dn = mysqli_real_escape_string($dbc, trim($_POST['doc_name']));
}
// Check for a document content:
if (empty($_POST['doc_content'])) {
$errors[] = 'You forgot to enter your last name.';
} else {
$dc = mysqli_real_escape_string($dbc, trim($_POST['doc_content']));
}
if (empty($errors)) { // If everything's OK.
// Test for unique doc title:
$q = "SELECT doc_id FROM docs WHERE doc_name='$dn' AND doc_id != $id";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 0) {
// Make the query:
$q = "UPDATE docs SET doc_name='$dn', doc_content='$dc', doc_name='$dn' WHERE doc_id=$id LIMIT 1";
$r = mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
$doc_id = mysqli_insert_id($dbc);
$query = "UPDATE doc_cat_join (cat_id,doc_id) VALUES ";
$cat_ids = $_POST['cat_id'];
$length = count($cat_ids);
for ($i = 0; $i < count($cat_ids); $i++) {
$query.='(' . $cat_ids[$i] . ',' . $doc_id . ')';
if ($i < $length - 1)
$query.=',';
}
// Print a message:
echo '<p>The document has been edited.</p>';
} else { // If it did not run OK.
echo '<p class="error">The document could not be edited due to a system error. We apologize for any inconvenience.</p>'; // Public message.
echo '<p>' . mysqli_error($dbc) . '<br />Query: ' . $q . '</p>'; // Debugging message.
}
} else { // Already used.
echo '<p class="error">The document name has already been used.</p>';
}
} else { // Report the errors.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p>';
} // End of if (empty($errors)) IF.
} // End of submit conditional.
// Always show the form...
// Retrieve the document's information:
$q = "SELECT * FROM docs WHERE doc_id=$id";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // Valid document ID, show the form.
// Get the document's information:
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
// Create the form:
echo '<form action="edit_doc.php" method="post">
<p>Document Name: <input type="text" name="doc_name" size="15" maxlength="15" value="' . $row[1] . '" /></p>
<textarea name="doc_content" id="doc_content" placeholder="Document Content" style="display: none;"></textarea>
<iframe name="editor" id="editor" ></iframe>'
?>
<div class="row">
<div class="col-group-1">
<?php
$q = "SELECT * FROM cats";
$r = mysqli_query ($dbc, $q); // Run the query.
echo '<div class="view_body">';
// FETCH AND PRINT ALL THE RECORDS
while ($row = mysqli_fetch_array($r)) {
echo '<br><label><input type="checkbox" name="cat_id[]" value="' . $row['cat_id'] . '">' . $row["cat_name"] . '</label>';
}
echo '</div>';
?>
</div>
</div>
<br><br>
<input onclick="formsubmit()" type="submit" value="Update Document" name="submit"/>
<?php echo'
<input type="hidden" name="id" value="' . $id . '" />
</form>
<br><br>Back to docs list';
} else { // Not a valid document ID.
echo '<p class="error">This page has been accessed in error.</p>';
}
?>
<?php
mysqli_close($dbc);
?>
So I have three tables:
docs
doc_id
doc_name
doc_content
cats
cat_id
cat_name
doc_cat_join
doc_id
cat_id
the join table related the doc_id and cat_id which then associates them together. I am guessing in my script when I update a doc it will need to delete the rows and then re-insert them? I just need to know a way or the easiest way of updating the join table as I am a tad stuck...
In case of checkbox update you need to delete previous stored checkbox of with appropriate id and insert new one you can't update checkbox as we can't predict how many checkbox will be selected by user....
Case:
It may happen that user remove one checkbox at update time so you will never know which one to be deleted.......
In your code...
docs
doc_id
doc_name
doc_content
cats
cat_id
cat_name
doc_cat_join
id
doc_id
cat_id
here you have to delete old checkbox of updation doc,
DELETE FROM doc_cat_join WHERE cat_id = some_id
next you can insert selected checkbox as you are inserting first time...
Hello
This part of a form is showing columns names from mysql table (names of applications installed on a computer) and creating a form with YES/NO option or input type="text" box for additional privileges to a application..
How can I insert it back to a mysql table using POST and mysql_query INSERT INTO?????
Quantity of columns is changing because there is another form for adding applications with/without privileges..
<tr bgcolor=#ddddff>';
//mysql_query for getting columns names
$result = mysql_query("SHOW COLUMNS FROM employees") or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
//exclude these columns bcs these are in other part of form
if($row[0] == 'id' || $row[0] == 'nameandsurname' || $row[0] == 'department'
|| $row[0] == 'phone' || $row[0] == 'computer' || $row[0] == 'data')
continue;
echo '<td bgcolor=#ddddff>'.$row[0].'<br />';
if (stripos($row[0], "privileges") !== false) {
echo '<td bgcolor=#ddddff><p><a class=hint href=#>
<input type="text" name="'.$row[0].'">
<span>Privileges like "occupation" or "like someone"</span></a></p></td></tr>';
}
else
{
echo '<td bgcolor=#ddddff align=center><select name="'.$row[0].'">
<option value = "No">No
<option value = "Yes">Yes
</td>
</tr>';
}
}
trim($_POST); // ????
$query = "INSERT INTO 'employees' VALUES (??)"; // ????
Because you're not inserting ALL columns, you need to dynamically build an insert statement that will specify the columns you're inserting into.
First, create an array of the columns you want to use. Use this both to generate your form and to retrieve the values
$exclude = array("id", "nameandsurname", "departument", "phone", "computer", "date");
$result = mysql_query("SHOW COLUMNS FROM employees") or die(mysql_error());
$columns = array();
while ($row = mysql_fetch_array($result)) {
if (!in_array($row[0], $exclude) {
$columns[] = $row[0];
}
}
Render your form from the $columns array:
foreach ($columns as $column) {
echo '<tr><td bgcolor="#ddddff">'.$column.'<br />';
if (stripos($column, "privileges") !== false) {
echo '<p><a class="hint" href="#">
<input type="text" name="'.$column.'">
<span>Privileges like "occupation" or "like someone"</span></a>';
} else {
echo '<select name="'.$column.'">
<option value = "No">No
<option value = "Yes">Yes
</select>';
}
echo '</td></tr>';
}
Then, dynamically build your INSERT string from the posted values for those columns. Be sure to protect against SQL injection:
$keys = array();
$values = array();
foreach ($columns as $column) {
$value = trim($_POST[$column]);
$value = mysql_real_escape_string($value);
$keys[] = "`{$column}`";
$values[] = "'{$value}'";
}
$query = "INSERT INTO 'employees' (" . implode(",", $keys) . ")
VALUES (" . implode(",", $values) . ");";
Note: this will work better if you select from INFORMATION_SCHEMA.COLUMNS so that you can know the type of column you're inserting into. That way, you won't have to quote everything.
<html>
<body>
<form action="dynamicinsert.php" method="POST" >
user name:<br>
<input type="text" id="username" name="username">
<br><br>
first name:<br>
<input type="text" id="firstname" name="firstname">
<br><br>
password:<br>
<input type="password" id="password" name="password">
<br><br>
<input type="submit" name="submit" value="add" />
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "you_DB_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function insertqueryfunction($dbfield,$table) {
$count = 0;
$fields = '';
foreach($dbfield as $col => $val) {
if ($count++ != 0) $fields .= ', ';
$col = addslashes($col);
$val = addslashes($val);
$fields .= "`$col` = '$val'";
}
$query = "INSERT INTO $table SET $fields;";
return $query;
}
if(isset($_POST['submit']))
{
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
$username_form = $_POST['username'];
$firstname_form = $_POST['firstname'];
$password_form = $_POST['password'];
$you_table_name = 'you_table_name';
$dbfield = array("username"=>$username_form, "firstname"=>$firstname_form,"password"=>$password_form);
$querytest = insertqueryfunction($dbfield,'you_table_name');
if ($conn->query($querytest) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
I have multiple text boxes displaying a string corresponding to a row in the mysql database. I want to be able to change each string in the database by typing in the textbox and clicking submit.
So I create my text boxes with a while loop after connecting to the DB.
<form action="<?php $self ?>" form method="post">
<?php
$query = "SELECT * FROM `table` ORDER BY table.ID DESC";
$result = #mysql_query($query) or die('
ERR: The database returned an unexpected error.
');
$num=mysql_numrows($result);
$change="";
$i=0;
while ($i < $num) {
$post=mysql_result($result,$i,"post");
$id=mysql_result($result,$i,"ID");
$ts=mysql_result($result,$i,"timeStamp");
$page = html_entity_decode($post);
$output = stripslashes($page);
if ($output != "") {
echo '<textarea name="' . $id . '" rows="4" cols="70">' . $output . '</textarea><div class="time"><font face="monospace">' . $ts . '</font></div>';
} //creates tables for each filled entry with a name corrsponing to its auto-increment id.
$i++;
}
?>
<input name="send" type="hidden" />
<div class="mod">
<p><input class="master" type="submit" value="Mod" /></p></div><!--submit button is called "Mod"-->
</form>
</body>
</html>
Everything displays properly. If the database has 4 rows with text in them than it will display those 4, each in a separate text box.
Now I want to replace the text in the database with whatever the user enters in the text boxes. This is the code I tried. It does nothing.
<?php
$i=0;
while ($i < $num) {
$id=mysql_result($result,$i,"ID");
$post=mysql_result($result,$i,"post");
if (!isset($_POST[$id])) {
$_POST[$id] = "";
}
$change = $_POST[$id];
mysql_query("UPDATE 'database'.'table' SET 'post' = '$change' WHERE 'table'.'ID' ='$id';");
$i++;
}
Basically the loop will run once for every row in the table. For every text box, it should UPDATE 'database'.'table' with $_POST[1] for 'post' with ID '1', $_POST[2] for 'post' with ID '2', etc...
Instead nothing happens.
Any help would be appreciated.
As Prowla mentioned , you should use PDO instead of mysql_ functions.
Anyway, I improved your code and it suppose to work now:
<form action="<?php $self ?>" form method="post">
<?php
$query = "SELECT * FROM `table` ORDER BY table.ID DESC";
$result = #mysql_query($query) or die('Query error:'.mysql_error());
$num=mysql_num_rows($result);
$change="";
while($post = mysql_fetch_array($result))
{
/*
$post = array(
'post' => '....',
'ID' => '...',
'timeStamp' => '...'
);
*/
$page = html_entity_decode($post['post']);
$output = stripslashes($page);
if ($output != "") {
echo '<textarea name="posts['.$post['ID'].']" rows="4" cols="70">' . $output . '</textarea><div class="time"><font face="monospace">' . $post['timeStamp'] . '</font></div>';
} //creates tables for each filled entry with a name corrsponing to its auto-increment id.
}
?>
<input name="send" type="hidden" />
<div class="mod">
<p><input class="master" type="submit" value="Mod" /></p></div><!--submit button is called "Mod"-->
</form>
</body>
</html>
The php update file:
$query = "SELECT * FROM `table` ORDER BY table.ID DESC";
$result = #mysql_query($query) or die('Query error:'.mysql_error());
while($update_post = mysql_fetch_array($result))
{
$update = (isset($_POST[$update_post['ID']])) ? $_POST[$update_post['ID']] : "";
if($update != "")
{
mysql_query("UPDATE 'database'.'table' SET 'post' = '$update' WHERE 'table'.'ID' ='".$update_post['ID']."';");
echo "<!--POST ID ".$update_post['ID']." been updated-->\n";
}
}
I added an html comment (<!-- -->) so you can check if the update actually takes place.
This way you can debug your code. (you should also read about print_r , var_dump)