I have problem with uploading files. Here is my form:
<form enctype="multipart/form-data" action="transact.php" method="POST">
<table>
<tr>
<td>Nadpis:</td>
<td><input type="text" id="title" name="title" value="<?php echo htmlspecialchars($title); ?>" /></td></tr>
<tr>
<td>Text článku:</td>
<td><textarea id="text" name="text" cols="55" rows="20"><?php if(!empty($a_text)) { echo htmlspecialchars($a_text); } ?></textarea></td>
</tr><tr>
<td>Obrázok k článku:</td>
<td><input type="file" name="uploadfile" /></td></tr>
<tr><td> </td>
<td>
<?php
if ($_SESSION['access_level'] < 2) {
echo '<input type="hidden" name="user_id" value="'. $user_id. '"/>';
}
if(empty($article_id)) {
echo '<input type="submit" name="action" value="Odoslat" />';
} else {
echo '<input type="hidden" name="article_id" value="' .$article_id. '"/>';
echo '<input type="submit" name="action" value="Ulozit" />';
}
?>
</td>
</tr>
</table>
</form>
when I run script transact.php I get error: Notice: Undefined index: uploadfile in E:\xampp\htdocs\capitals\transact.php on line 138
and when I type print_r($_FILES) i get just Array()
value of max upload size in php.ini file is set to 128 MB
my transact script:
case 'Odoslat':
session_start();
$text = (isset($_POST['text']))? $_POST['text']: '';
$nadpis = (isset($_POST['title']))? $_POST['title']: '';
$image = (isset($_FILES['uploadfile']))? imagecreatefromjpeg($_FILES['uploadfile']['tmp_name']): '';
print_r($_FILES); // it writes Array()
if(isset($_SESSION['id']) && !empty($nadpis) && !empty($text) && $_FILES['uploadfile']['error'] == UPLOAD_ERR_OK) //here it indicates error
{
$ext = '.jpg';
$query = 'INSERT INTO articles (article_id, user_id, a_text, title, submit_date)
VALUES(NULL, '. $_SESSION['id']. ', "'. mysql_real_escape_string($text, $db). '", "'.
mysql_real_escape_string($nadpis, $db). '", "' . date('Y-m-d H:i:s'). '")';
mysql_query($query, $db) or die(mysql_error($db));
$clanok_id = mysql_insert_id($db);
$query = 'INSERT INTO foto (foto_id, article_id)
VALUES (NULL, '. $clanok_id. ')';
mysql_query($query, $db) or die(mysql_error($db));
if(!empty($image))
{
$last_id = mysql_insert_id($db);
$image_name = $last_id. $ext;
imagejpeg($image, $dir. '/'. $image_name, 100);
}
else
{
$last_id = mysql_insert_id($db);
$image_name = 'caps.jpg';
}
$priecinok = 'images/';
$place = $priecinok. $image_name;
$query = 'UPDATE foto
SET foto_path = "'. $place. '" WHERE foto_id = '. $last_id;
mysql_query($query, $db) or die(mysql_error($db));
$query = 'UPDATE articles
SET foto_id = '. $last_id. ' WHERE article_id = '. $clanok_id;
mysql_query($query, $db) or die(mysql_error($db));
$redirect = 'index.php';
}
else
{
$chyba = 'Nepodarilo sa nahrat clanok!';
$redirect = 'index.php?chyba='. $chyba;
}
break;
Please how can I repare it? I will be very grateful if somebody help me...
There are 4 things you should check in your php.ini file to make sure file uploads will work :
file_uploads : should be set to 1
upload_max_filesize : should be set to a value big enough for what you plan on uploading. You said it's set to 128 MB. Make sure it is written as '128M'.
post_max_size : should be set to a value higher than upload_max_filesize since it includes the files and the other post data
max_file_uploads : less important, but it limits the number of files you can upload at once
One of the most important apasrt from php.ini setting is ,please check whether you have permission to write in that particular folder where you are uploading the image.
Try add this in your form:
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
this value set maximum file to 100KB.
Related
I need to put the value '0' in the database without having to fill in a text field.
Is there any way to give a column the value '0', when i save a form in the database?
This is the form:
<form action="<?php echo $base_url; ?>" method="post" enctype="multipart/form-data">
<table class="sug" width="300">
<tr><td><input type="text" name="naam" placeholder="Naam" required></td>
<td><input type="text" name="level" placeholder="Level"></td></tr>
<tr><td colspan="2"><textarea placeholder="Beschrijving" name="beschrijving" maxlength="200"></textarea></td></tr>
<tr><td><input type="file" name="afbeelding" required id="afbeelding"></td></tr>
<tr><td><input type="submit" name="add" value="Toevoegen"/>
</td></tr>
</table>
</form>
The save function:
if (!empty($post_array)) {
// Check the add form:
$add = FALSE;
if (isset($post_array['add'])) {
// Save images
$check = getimagesize($_FILES["afbeelding"]["tmp_name"]);
if ($check !== false) {
//echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Upload afbeelding
$projecten->upload($_FILES['afbeelding']);
// Save project
$result = $projecten->save($post_array);
if ($result) {
// Save was succesfull
$add = TRUE;
} else {
// Indicate error
$error = TRUE;
}
}
}
public function save($input_array) {
global $wpdb;
// Insert query
$wpdb->query($wpdb->prepare("INSERT INTO `" . $wpdb->prefix . "ivs_canvas_tabel`
( `naam`, `level`, `beschrijving`, `afbeelding`)" .
" VALUES ( '%s', '%s', '%s', '%s');", $input_array['naam'], $input_array['level'], $input_array['beschrijving'], $_FILES['afbeelding']['name']));
// Error ? It's in there:
if (!empty($wpdb->last_error)) {
$this->last_error = $wpdb->last_error;
return FALSE;
}
return TRUE;
}
I have no idea how to add the field, i hope someone can help me out!
Yours sincerely
You can do this using input with hidden attribute in form:
<input type=“hidden” name=“colom” value=“0” />
You can put default value in your database:
alter table `table_name`
modify column `column_name` int default 0;
I have a table named positions. This table has the list of the different positions that the admin has added in the listOfPositions.php like President, Vice-President, etc. After adding different positions, he can now add the different people under that position. And that's where my problem is. How will I have an auto increment input name for the names of the people depending on how many positions it has in the table positions ?
I tried using javascript, but it increments only in the html and not reflecting to the php when I try to save. My current code where the adding of the names of different persons depending on the position is the ff:
<script type="text/javascript" src="http://code.jquery.com/jquery-git.js"></script>
<form action="post_officers.php" method="post"><br>
<center><select name="year">
<?php
for($i=date('Y'); $i>1999; $i=$i-2) {
$selected = '';
$year2 = $i-2;
if ($year == $i) $selected = ' selected="selected"';
echo ('<option value="'.$year2. "-" . $i .'" '.$selected.'> '.$year2.'-'.$i.'</option>'."\n");
}
?>
</select></center>
<?php
include_once('dbcontroller.php');
$sql = "SELECT * FROM positions ORDER BY pos_id ASC";
$result = mysqli_query($conn, $sql);
/* assign an onchange event handler */
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<br><br>
<table id="options-table">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="hidden" name="position" /><?php echo $position; ?></td>
<td><input type="text" name="name" /></td>
</tr>
</table>
<?php
}
?>
<input type="submit" name="submit" value="SAVE"/>
</form>
<script>
$("input[name='file']").each(function(ind) {
$(this).attr(ind + 1);
});
$("input[name='position']").each(function(ind) {
$(this).attr(ind + 1);
});
$("input[name='name']").each(function(ind) {
$(this).attr(ind + 1);
});
</script>
And this is my php code:
<?php
include ('dbcontroller.php');
date_default_timezone_set('Asia/Manila');
$year = mysqli_real_escape_string($conn,$_POST['year']);
if(isset($_POST['submit'])) {
$result = mysqli_query($conn,"SELECT * FROM officers WHERE year = '$year'");
$num_rows = mysqli_num_rows($result);
if($num_rows>0){
echo "<script type='text/javascript'>alert('Year already exists.'); window.location.href='create_alumni_officers.php';</script>";
}
else {
for ($i = 1; $i <= 8; $i++) {
$name = mysqli_real_escape_string($conn,$_POST['name'.$i]);
$position = mysqli_real_escape_string($conn,$_POST['position'.$i]);
$file=(rand(1000,100000)."-".$_FILES['file'.$i]['name']);
$type=($_FILES['file'.$i]['type']);
$size=$_FILES['file'.$i]['size'];
$loc=($_FILES['file'.$i]['tmp_name']);
$new_size=$size/1024; // file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($loc, '../officers-avatars/'.$final_file)) {
echo "Page is loading, please wait...";
$result = mysqli_query($conn,"INSERT INTO officers VALUES (id, '$year', '$position', '$name', '$final_file', '$new_size', '$type')")
or die(mysqli_error($conn));
echo ("<script type='text/javascript'>window.location.href='alumni_officers.php';</script>");
}
}
}
}
?>
And this doesn't work at all. Any help? I hope you guys understood what I'm trying to ask.
This is the best way to do it:
<?php
include_once('dbcontroller.php');
$sql = "SELECT * FROM positions ORDER BY pos_id ASC";
$result = mysqli_query($conn, $sql);
/* assign an onchange event handler */
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<table id="options-table">
<tr>
<td><input type="file" name="file[<?php echo $position; ?>]" /></td>
<td><input type="hidden" name="position[<?php echo $position; ?>]" value="<?php echo $position; ?>" /><?php echo $position; ?></td>
<td><input type="text" name="name[<?php echo $position; ?>]" /></td>
</tr>
</table>
<?php
}
?>
You don't need the javascript to change input attributes. Remove it.
In php use foreach loop like:
If you are still getting errors I will need to see the output of print_r($_POST);
<?php
$files = $_FILES['file'];
$positions = $_POST['position']; //use this for the foreach loop because it will always have a value
$names = $_POST['name'];
foreach($positions as $key=>$position){
$file = #$files[$key];
$name= #$names[$key];
//Do your magic for each user here
$name = mysqli_real_escape_string($conn,$name);
$position = mysqli_real_escape_string($conn,$position);
$filename = rand(1000,100000)."-".$file['name'];
$type = $file['type'];
$size = $file['size'];
$loc = $file['tmp_name'];
$new_size=$size/1024; // file size in KB
// make file name in lower case
$new_file_name = strtolower($filename);
// make file name in lower case
$final_file = str_replace(' ','-',$new_file_name);
if(move_uploaded_file($loc, '../officers-avatars/'.$final_file)) {
echo "Page is loading, please wait...";
$result = mysqli_query($conn,"INSERT INTO officers VALUES (id, '$year', '$position', '$name', '$final_file', '$new_size', '$type')")
or die(mysqli_error($conn));
echo ("<script type='text/javascript'>window.location.href='alumni_officers.php';</script>");
}
}
?>
As I indicated in the contents, removing context switches miss fide will greatly increase the readability of your code. I'll illustrate below a bit as well as answer the question.
To get what you're after, you could do this:
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<br><br>
<table id="options-table">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="hidden" name="position" /><?php echo $position; ?></td>
<td><input type="text" name="name<?php echo $position; ?>" /></td>
</tr>
</table>
<?php
}
However, to illustrate a small example of removing these contextual switches mid code, see below and pardon but this is air code, if you want a more specific example, just ask.
Let's say you often use the tag thoughout your site in forms. You could drop out of php each time and just write out the straight html. Or, you could create a class, or even a simple function for the html output thusly:
Function opt($int, $parms = '') {
Return '<Option '.$parms.'>'. $int.'</option>';
}
Now your code would look more like this:
While ($r =mysqli_fetch_array ($result)) {
Extract ($r); // learn this, no sense assigning them 1 by 1
$options .= opt($databaseobject, 'name="foo" value="'. $databaseobjectid.'"');
}
Echo $options;
I'm sorry if this is a repost. But I have seen many questions without finding the right answer
i'm trying to upload multiple files + some information , but if i submit my form with 2 images it goes ok and the script runs perfect when i upload more then 2 or 3 files i get undefined indexs of all the form elements .
up.php
/////// Random name generator ////////
function random_name($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
//sql//
require("sql.php");
//////////
//!!! some vars !!!//
//
$total = count($_FILES['pimages']['name']);
//
$foldername = random_name(15);
$target_dir = "../images/projects/".$foldername."/";
$target_file = $target_dir . basename($_FILES["icon"]["name"]);
$uploadyes = 1;
$imageType = pathinfo($target_file,PATHINFO_EXTENSION);
$saveicon = $target_dir . "icon." .$imageType;
/////submited form vars /////
$linkedid = $_POST['lid'];
$date = date("y.m.d H:i:s");
$name = $_POST['projectname'];
$loc = $_POST['location'];
$type = $_POST['type'];
$des = $_POST['des'];
$precara = $_POST['cara'];
$client = $_POST['client'];
$col = $_POST['cost'];
$bua = $_POST['builtup'];
////////////////cara slice /////////////
$caraxarray = explode("," , $precara);
$cara = base64_encode(serialize($caraxarray));
echo $imageType ;
///////////////////////// Start of the upload check ////////////////////
if(isset($_POST['submit']) && !empty($name)) {
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
}
// Check if $uploadyes is set to 0 by an error
if (!isset($_POST['submit'])) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
mkdir($target_dir);
if (move_uploaded_file($_FILES["icon"]["tmp_name"], $saveicon)) {
//////////////////////////..........................//////////////////
// Loop through each file
$imgext = array();
for($i=0; $i<=$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['pimages']['tmp_name'][$i];
$x = $i + 1 ;
if ($tmpFilePath != ""){
//Setup our new file path
$pimgex = $_FILES['pimages']['name'][$i];
$pimageType = pathinfo($pimgex,PATHINFO_EXTENSION);
$newFilePath = $target_dir ."img".$x.".".$pimageType;
array_push($imgext , "$newFilePath");
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo "yeaaaaaah";
}
}
}
$str = serialize($imgext);
$sql1 = "INSERT INTO projects (date, name, type, location, icon, imgext, folder, linkedid)
VALUES ('$date', '$name','$type', '$loc', '$saveicon' , '$str', '$foldername', '$linkedid')";
$sql2 = "INSERT INTO projectdetails (proname, prolocation, prodes, procara, client, col, builtarea, linkedid)
VALUES ('$name', '$loc','$des', '$cara', '$client' , '$col', '$bua', '$linkedid')";
mysqli_query($conn ,$sql1);
mysqli_query($conn ,$sql2);
mysqli_close($conn);
/////////////////...........................////////////////////////
header("location:cp.php");
} else {
echo "Sorry, there was an error uploading your file.";
}
}
projectsuploader.php
$lkid = random_name(8);
$tlink = random_name(6);
require("sql.php");
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql1 = "SELECT id, date, name, type, location FROM projects";
$sql2 = "SELECT id, titleen FROM projectsnav";
$result = mysqli_query($conn, $sql1);
$types = mysqli_query($conn, $sql2);
//mysqli_close($conn);
?>
<!DOCTYPE html>
<html>
<h2>Projects Page</h2>
<h5>projects</h5>
<table>
<tr>
<td>#</td>
<td>Date & Time</td>
<td>Project name</td>
<td>Project type</td>
<td>Project location</td>
<!--<td>View</td>
<td>Edit</td>-->
<td>Remove</td>
</tr>
<?php
if (mysqli_num_rows($result) > 0) {
// output data of each row .$row["id"]
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row["id"]."</td>";
echo "<td>".$row["date"]."</td>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["type"]."</td>";
echo "<td>".$row["location"]."</td>";
echo "<td><a href='../del.php?id=".$row['id']."'>Remove</a></td> </tr>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</table>
<h4 id="addproject">Add Project</h3>
<h4 id="addtype">Add Type </h4>
<div id="frontlayer">
<div id="addpro">
<h2 style="text-align:center;"> add project </h2>
<form method="POST" action="up.php" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="50000000">
id:<input type="text" name="lid" value="<?php echo $lkid ; ?>" readonly> <br>
project name:<input type="text" name="projectname"><br>
Type:<select name="type">
<?php
if (mysqli_num_rows($types) > 0){
while($navrow = mysqli_fetch_assoc($types)) {
echo "<option value='".$navrow['titleen']."'>".$navrow['titleen']." </option>";
}
}else{
echo "<option>PLEASE ADD TYPES TO DATABASE FIRST!!!!ERROR 0 TYPES IN DATABASE</option>";
}
mysqli_close($conn);
?>
</select>
<br>
location:<input type="text" name="location"><br>
icon:<input type="file" name="icon" id="icon"><br>
images:<input type="file" name="pimages[]" id="pimages" multiple><br>
<input type="hidden" name="sendfiles" value="Send Files" />
<!--
------//////////////------
------//////////////------
------//////////////------
-->
description:<input type="text" name="des"><br>
caracteristic:<input type="text" name="cara" data-role="tagsinput"><br>
client:<input type="text" name="client"><br>
Collaborator:<input type="text" name="cost"><br>
Gross Area:<input type="text" name="builtup"><br>
<input type="submit" value="Upload" name="submit">
</form>
</div>
Sorry if it is bad writed i\m begginer , Thanks in advance for anyhelp
The problem were that there was a big file (4mb image) and php was not able to post this size of an image so you have to resize your image before upload ..
and big thanks for Felippe Duarte.
I do have programming experience, but new to php. I do have an issue with an example I was doing from this tutorial. I looked over it millions of times, googled, ect ect. I don't have an idea why my code isnt working.
The purpose is to basically just test inserting and deleting in sql from php, using a button for Add Record and Delete Record. The Add record button works perfectly, but delete doesnt do a thing other than reload the page. Heres the code...
<?php // sqltest.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['type']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$type = get_post('type');
$year = get_post('year');
$isbn = get_post('isbn');
if (isset($_POST['delete']) && $isbn != "")
{
echo "worked!!!!!!!!!!!!!!";
$query = "DELETE FROM classics WHERE isbn='$isbn'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows($result) > 0) echo 'user deleted';
//if (!mysql_query($query, $db_server))
//echo "DELETE failed: $query" . mysql_error();
}
else
{
echo "nooooooooooooooooooo";
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$type', '$year', '$isbn')";
if (!mysql_query($query, $db_server))
{
echo "INSERT failed: $query" . mysql_error();
}
}
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Type <input type="text" name="type" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type='submit' value='ADD RECORD' />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Type $row[2]
Year $row[3]
ISBN $row[4]
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name='isbn' value="$row[4]" />
<input type='submit' value='DELETE RECORD' />
</form>
</pre>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
I have looked over this many times, still no idea why this won't work. Is it the for loop that is making this button not work? Note, you will see echo "worked!!!"; and in the else echo "noooooooo"; that was for me to test whether the button was being tested, yet nothing prints. So maybe i missed something in the button code itself? Also, no errors are printed, and my editor (and myself) have missed the syntax error (if thats the case).
The code for the delete button is at the end, before I closed the DB.
Thanks for your help in advance.
Your problem is your first if block.
You're checking for the presence of the posted variables author title type year isbn. Whereas in your delete code the only variables sent are delete and isbn. Therefore the first if block is completely missed (including the delete code).
You need to modify your first if to be if(isset($_POST)) { // a form has been posted. Then it should work.
Another way to do it:
if(isset($_POST['delete']) && isset($_POST['isbn']) && !empty($_POST['isbn'])){
//delete code here
}
if(isset($_POST['author']) && isset($_POST['title']) && isset....){
// insert code here
}
EDIT: rewritten code:
<?php // sqltest.php
// I don't know what's in here, so I've left it
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST))
{
if (isset($_POST['delete']) && !empty($_POST['isbn']))
{
echo "Deleting";
$query = "DELETE FROM classics WHERE isbn='".mysql_real_escape_string($_POST['isbn'])."'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows($result) > 0) echo 'user deleted';
}
else
{
echo "Inserting";
$query = "INSERT INTO classics VALUES ('".mysql_real_escape_string($_POST['author'])."', '".mysql_real_escape_string($_POST['title'])."', '".mysql_real_escape_string($_POST['type'])."', '".mysql_real_escape_string($_POST['year'])."', '".mysql_real_escape_string($_POST['isbn'])."')";
if (!mysql_query($query))
{
echo "INSERT failed: $query" . mysql_error();
}
}
}
// you don't need echo's here... just html
?>
<form action="sqltest.php" method="post">
<pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Type <input type="text" name="type" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type='submit' value='ADD RECORD' />
</pre>
</form>
<?php
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
// a better way to do this:
while($row = mysql_fetch_array($result)){
?>
<pre>
Author <?php echo $row[0]; ?>
Title <?php echo $row[1]; ?>
Type <?php echo $row[2]; ?>
Year <?php echo $row[3]; ?>
ISBN <?php echo $row[4]; ?>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name='isbn' value="<?php echo $row[4]; ?>" />
<input type='submit' value='DELETE RECORD' />
</form>
</pre>
<?php
}
mysql_close($db_server);
?>
Verify the method you used in your form. Make sure it's POST like this:
Form action="yourpage.php" method="POST"
and in your code above, replace the following:
$author = get_post('author');
$title = get_post('title');
$type = get_post('type');
$year = get_post('year');
$isbn = get_post('isbn');
with
$author = $_POST['author'];
$title = $_POST['title'];
$type = $_POST['type'];
$year = $_POST['year'];
$isbn = $_POST['isbn'];
Finally, there is no need to check again if the $isbn is not null as you did it in your isset() method. So remove $isbn!="" in the if below:
if (isset($_POST['delete']) && $isbn != "")
{
}
becomes:
if (isset($_POST['delete']))
{
}
Since you are testing, checking if the user clicked the delete button is of less importance. So you can also remove it for a while and add it later because you are sure that, that code is accessible after clicking the delete button.
You have no form field named delete, so it is impossible for your delete code path to ever be taken.
I'm guessing you're tryign to use the value of the submit button to decide what to do? In that case, you're also missing a name attribute on the submit button - without that, it cannot submit any value with the form. You probably want:
<input type="submit" name="submit" value="DELETE RECORD" />
and then have
if (isset($_POST['submit']) && ($_POST['submit'] == 'DELETE RECORD')) {
...
}
I have a php page with form for updating records and image I don’t know what is wrong with the update statement ,,, the values of fields are taken and I can see them on url through the GET method ... But when I run the page and update record information is not changing and nothing appear on the page ,,, since none of fields r taking the update I think my update statement having problem ,,,here is the code:
<?php
// Connect to the database
require("includes/conn.php");
// Script Variables
$target_dir = 'images/';
$file_given = false;
$inputs_given = false;
$id_given = false;
if(isset($_POST['serialid']) && $_POST['serialid'] != "")
{
$serialid = $_POST['serialid'];
$id_given = true;
}
// You only need to catch input from a create or modify action, so start by checking for ALL the REQUIRED inputs
if(isset($_POST['name']) && $_POST['name'] != "" && isset($_POST['description']) && $_POST['description'] != "" && isset($_POST['price']) && $_POST['price'] != "")
{
$name = $_POST['name'];
$paragraph = $_POST['description'];
$price = $_POST['price'];
if(isset($_POST['picture']) && $_POST['picture'] != "")
{
$picture = basename($_FILES['picture']['name']);
$file_given = true;
}
// Just some verification (not really much, but you can write your own functions and slot them in
$name_safe = true;
$description_safe = true;
$price_safe = true;
$picture_safe = false;
if($_FILES["picture"]["type"] == "image/gif" || $_FILES["picture"]["type"] == "image/jpg" || $_FILES["picture"]["type"] == "image/png" || $_FILES["picture"]["type"] == "image/bmp")
$picture_safe = true;
if($name_safe && $description_safe && $price_safe && $picture_safe)
$inputs_given = true;
}
if($id_given && $inputs_given)
{
// Search for the record and see if it exists
$get_record = mysql_query("SELECT serial, picture FROM products WHERE serial='$serialid'");
$record_exists = mysql_num_rows($get_record);
if($record_exists == 1)
{
if($file_given)
{
$update_image = ", picture='$picture'";
// Now we need to remove the old image from the file system and upload our new one in it's place
$previous_image = mysql_result($get_record,'0','picture');
unlink($target_dir . $previous_image);
//Now that the previous image has been removed, we need to upload our new image
$new_image = $target_dir . $picture ;
move_uploaded_file($_FILES['picture']['tmp_name'], $new_image);
}
else
$update_image = "";
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price', " . $update_image . " WHERE serial='$serialid'"))
$action_output = "Record successfully modified.";
else
$action_output = "Record modification unsuccessful.";
}
else
$action_output = "The record id you specified does not exist.";
}
?>
<html>
<head>
<title>Manage Records</title>
</head>
<body>
<?php echo $action_output; ?>
</body>
</html>
<?php
// Disconnect from the database
?>
Here is the url when I click the modify
http://localhost/Shopping/update.php?name=View+Sonic+LCD&description=LCD&price=250&picture=C%3A%5CDocuments+and+Settings%5Ce2565%5CMy+Documents%5CTwasul%5Ctlogo%5Cicon%5Cpic1.jpg&serialid=1
My Modify Form is this
<?php
// Connect to the database
require("includes/conn.php");
$id_given = false;
if(isset($_POST['serialid']) && $_POST['serialid'] != "")
{
$serialid = $_POST['serialid'];
$id_given = true;
}
if($id_given)
{
$get_record = mysql_query("SELECT * FROM products WHERE serial='$serialid'");
$record = mysql_fetch_array($get_record);
$output = '<form method="POST" enctype="multipart/form-data" action="update.php?serialid=' . $record['serialid'] . '&action=modify">
<table>
<tr>
<td>Name:</td>
<td><input name="name" type="text" value="' . $record['name'] . '"/></td>
</tr>
<tr>
<td>Description :</td>
<td><textarea name="description" cols="45" rows="5">' . $record['description'] . '</textarea></td>
</tr>
<tr>
<td>Price:</td>
<td><input name="price" type="text" value="' . $record['price'] . '"/></td>
</tr>
<td colspan="2"><img height="50" width="50" src="../images/' . $record['picture'] . '"/><br/>' . $record['picture'] . '</td>
</tr>
<tr>
<td>Modify Image:</td>
<td><input name="picture" type="file" value="" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Modify Record"/>
</td>
</tr>
</table>
</form>';
}
else
$output = 'No record id was specified.';
?>
<html>
<head>
<title>Modify Record</title>
</head>
<body>
<?php echo $output; ?>
</body>
</html>
<?php
// Disconnect from the database
?>
First, you have an extra comma in this line, before the WHERE :
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price', " . $update_image . " WHERE serial='$serialid'"))
The correct syntax is :
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price' " . $update_image . " WHERE serial='$serialid'"))
Then, you said
I can see them on url through the GET method
But in your script you are using $_POST variable to get values, use $_GET instead or change the method of your form to post.
If you want to upload a picture you have to use post method, the file will be available in the $_FILES variable.
In your example, you pass parameters by URL so, with the get method, and the "picture" is just the path to the picture in your PC, and it's not uploaded on the server.
EDIT :
Add "<input type='hidden' name='serialid' value='".$record['serialid']."' />" AND "<input type='hidden' name='action' value='modify' />" in your form instead of add this parameters to the action url of it, and it should work
you have added comma in $update_image = ", picture='$picture'"; as well as in
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price', " . $update_image . " WHERE serial='$serialid'"))
either remove the comma in $update_image = " picture='$picture'"; or remove in this
if(mysql_query("UPDATE products SET name='$name', description='$description', price='$price' " . $update_image . " WHERE serial='$serialid'"))'