update statement with image - php

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'"))'

Related

Passing data to another page after form submit with PHP

I've read through a number of similar questions, so I know this has been answered before, but now my question is why isn't what I'm doing working?
I'm new to web development, developing a web form that passes the submitted data to a CSV file. What I currently do, is after all form validation is done on the form page "form.php", it sends the user to another page "submittedApplication.php", and in the same statement goes all of my code to push the data into a CSV.
What I NEED, is to pass one particular variable from "form.php", over to "submittedApplication.php". It's a reference number that I have a random generator for, on form.php.
In my code I use a function to create the reference number, I store it in a variable called $result. In the bottom of the validation I use
header('Location: submittedApplication.php?result={$result}');
to try and pass it over, and then in the second page I use
echo $_GET['result'];
to try and grab the variable.
If you spot it in my code, I've also tried the hidden input method, to no avail as well.
Here is my form.php main page
<!DOCTYPE html>
<html>
<?php
//Define variables and set to empty values
//###CUSTOMER DATA###
//Name
$custName= "";
$custNameError = "";
//Reference Number
$result = gen_uid();
//Error holders
$errors = ""; //Generic Error list at top of form, can be appended to
$error = 0; //Error Tally, If 0 = good. If 1 = error.
//Generates a 10 character random string with a prefix and current date attached
function gen_uid($l=10){
$prefix = "BLANK DATA#";
$str = "";
date_default_timezone_set('America/New_York');
$date = date("Y.m.d");
for ($x=0;$x<$l;$x++)
$str .= substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1);
echo $prefix . $str . "<br/>" . "Generated On: " . $date; }
//for testing
echo $result;
if($_SERVER["REQUEST_METHOD"] == "GET"){
$custName = "";
$custAddress = "";
}
else if ($_SERVER["REQUEST_METHOD"] == "POST") { // Checking null values in message.
$custName = $_POST['customername'];
$custAddress = $_POST['CustomerMailingAddress'];
$passedResult = $_POST['result'];
//################################## Form Validation #####################################
//CUSTOMER NAME
if(!isset($custName) || $custName == "")
{
$custNameError = "Name required";
$errors .= "Customer contact information required, Contractor optional.<br/>";
$custName = "";
$error = 1;
}
else{
$custName = $_POST['customername'];
}
if($error == 0)
{
echo "<input type='hidden' name='result' value='{$result}'/>";
//this is where the creating of the csv takes place
$cvsData = $custName . "," . $custAddress . "," . $custPhone . "," . $custMobile . "," . $custFax . "," . $custEmail . "," . $conName . "," . $conAddress . "," .
$custPhone . "," . $conPhone . "," . $custMobile . "," . $conMobile . "," . $custEmail . "," . $conEmail . "," . $accNum ."\n";
$fp = fopen("formTest.csv","a"); // $fp is now the file pointer to file $filename
if($fp){
fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file
}
header('Location: submittedApplication.php?result={$result}');
}
}
?>
<body>
<h2 align="center"><u>Service Request Application Form</u></h2>
<hr>
<h4>NOTES:</h4>
<div id="wrapper">
<br/>
<h3 class="error"><?php echo $errors; ?></h3>
<form method="post" align="center" name="applicationform" id="applicationform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" enctype="multipart/form-data">
<!--###################################### CONTACT INFORMATION FIELDSET ######################################-->
<fieldset style="border: 1px black solid" align="center">
<legend style="font-weight:bold"><u>Contact Information</u></legend>
<table>
<tr>
<th></th>
<th><u>Customer</u></th>
<th title="Electrician"><u>Consultant/Contractor</u></th>
</tr>
<tr>
<td>
<tr>
<td align="right" id="namelabel">Contact Name:</td>
<td><input type="text" id="customername" name="customername" value="<?php echo $custName;?>" title="Name of contact on account"/></td>
<td><input type="text" id="contractorname" name="contractorname" title="Name of contractor or consultant" /></td>
</tr>
<tr>
<td></td>
<td><div class="error"><?php echo $custNameError;?></div></td>
<td></td>
</tr>
</td>
</tr>
</table>
</table>
</form>
</div>
</body>
</html>
And here is my second page submittedApplication.php
<!DOCTYPE html>
<html>
<body>
<h2 align="center"><u>Service Request Application Form</u></h2>
<hr>
<h4>NOTES:</h4>
<hr>
<div align="center"><h3>Application Submitted Successfully!</h3> </div>
<?php
echo $_GET['result'];
?>
</body>
</html>
Any and all tips are appreciated!
The way I would normally tackle passing values between pages is to use session variables.
You can do this in your form.php page
session_start();
$SESSION_["result"] = $result;
Then do the following in your other page
session_start();
if(isset($SESSION_["result"]) {
$result = $SESSION_["result"];
}
Just make sure you destroy or unset any session variables when you're done with them.

Error in updating a mysql table

here I'm trying to display the record of a member and trying to edit the details.
First, I'm fetching the details from a database into textboxes, then, when I should hit the submit button..it should update the entry which is updated and should keep the original value of the textbox which is not updated.
Here's the code :-
The first one is of editmember.php
<?php
session_start();
include 'dbconnector.php';
$receivedusername=$_REQUEST['username'];
$parentusername=$_SESSION['username'];
$_SESSION['cusername']=$receivedusername;
//check session
if((isset($_SESSION['logged'])) && ($_SESSION['logged']==1))
{
//now map the user to it's parent account
$query="select * from master_member where parentusername = '" . $parentusername . "' and currentusername = '" . $receivedusername . "'";
$result=mysql_query($query,$db) or die (mysql_error($db));
if(mysql_num_rows($result) > 0)
{
$row=mysql_fetch_assoc($result);
//account mapped, green signal to proceed
?>
<form action="memberaction.php?action=edit" method="post">
<table>
<tr>
<td>Username : <input type="text" name="usrnm" value="<?php echo ($row['currentusername']); ?>" /></td>
</tr>
<tr>
<td>Email : <input type="text" name="eml" value="<?php echo ($row['currentemail']); ?>" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
<?php
}
else
{
echo "You aren't authorized to perform this task, redirecting.";
header('refresh:2;URL=members.php');
exit();
}
}
else
{
header('Location:login.php');
exit();
}
?>
memberaction.php
case 'update':
$memberusername=$_SESSION['cusername'];//username of the member, whose account is to be edited.
$parentusername=$_SESSION['username'];//username of the parent.
//since the account is already matched to the parent account before, we do not need to do it again.
//get the field value
$usrnm=(isset($_POST['usrnm'])) ? $_POST['usrnm'] : '';
$eml=(isset($_POST['eml'])) ? $_POST['eml'] : '';
$query="update master_member set currentusername = '" . $usrnm . "' and currentemail = '" . $eml . "' where parentusername = '" . $parentusername . "' and currentusername = '" . $memberusername . "'";
$result=mysql_query($query,$db) or die (mysql_error($db));
if($result)
{
echo "updated";
header('refresh:2;URL=members.php');
exit();
}
else
{
echo "Errors";
}
break;
After I hit the submit button, it displays successfully updated, but no change takes place at the database.
What possible mistake I'm doing ?
My DB structure is like :-
http://sqlfiddle.com/#!2/969c54/2

Create input fields dynamically with values and column names from database

I create inputs using the information in the columns for example if a field is called about_content it outputs a label of About Content with an input field. This works fine for inserting however I want to use this code similarly to UPDATE and I want to display to users the current value of a field as entered in the database. For example if about_content = Hello World! I want the input value to reflect that. Is there a way of doing this dynamically?
<?php
require('dbc.php');
mysql_select_db($db);
$resultInput = mysql_query("SHOW COLUMNS FROM about WHERE Field NOT IN
('id', 'created', 'date_modified', 'last_modified', 'update', 'type', 'bodytext')
AND Field NOT REGEXP '_image'"); // selects only the columns I want
$result = mysql_query("SELECT * FROM about WHERE id=".$_GET['id']); // values I want to put into the values for <input>
while ($row = mysql_fetch_assoc ($result) && $column = mysql_num_rows ($resultInput)) {
foreach($row as $column => $value){
echo '<label>'.$column.'<input name="'.$column.'" type="input" value="'.$value.'"></label><br>';
}
}
?>
See the spot you've marked with an arrow? Instead of the string (1), set value to the appropriate database value you read in $result (not in $resultInput).
Here's how: use mysql_fetch_assoc for your SELECT query, not mysql_fetch_row. There will be only one row, so fetch it before you start generating the form. You'll then have a named array with the row values, and you can grab each field by name and put it in the form.
If you don't understand how to do that, check the php documentation for mysql_fetch_assoc.
And escape your $_GET['id'] like you were told in your last question. You're begging to be pwned!
See mysql_fetch_field.
if (mysql_num_rows($result) > 0) {
//loop creates inputs
//make $resultInput object to array.
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$meta = mysql_fetch_field($result, $i);
if(in_array($meta->name, $resultInput )){
echo '<div class="wrapper"><label>' . ucfirst(str_replace('_', ' ',$meta->name)) .
'<br><input name="' . $meta->name .
'" type="text" class="input" value="$row[$meta->name]"><br></label></div>';
}
$i++;
}
}
<?php
include('db.php');
if (isset($_POST['btn'])) {
$dcolumn = $_POST['dyncolumns'];
$dvalue = $_POST['dynfields'];
$name = $_POST['name'];
$mobile = $_POST['mobile'];
$address = $_POST['address'];
$query = "INSERT into addtable(name,mobile,address)VALUES('" . $name . "','" . $mobile . "','" . $address . "')";
$result = mysql_query($query)or die(mysql_error());
$id = mysql_insert_id();
if ($dcolumn) {
foreach ($dcolumn as $key => $value) {
$result1 = "show COLUMNS from addtable like '.$value.'";
$exists = mysql_query($result1)or die(mysql_error());
$data = mysql_fetch_assoc($exists);
if ($data==TRUE) {
$query = "update addtable set $value = '" . $dvalue[$key] . "' where id=$id";
} else {
$query1 = "ALTER TABLE addtable ADD $value varchar(45)";
$result2 = mysql_query($query1)or die(mysql_error());
$query = "update addtable set $value = '" . $dvalue[$key] . "' where id=$id";
$result = mysql_query($query)or die(mysql_error());
}
}
}
}
?>
<script>
function myFunction() {
var table = document.getElementById("insert");
var row = table.insertRow(3);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "<input type='text' name='dyncolumns[]'>";
cell2.innerHTML = "<input type='text' name='dynfields[]' >";
}
</script>
<html>
<body>
<form name="insert" method="post">
<table border="2" align="center" id="insert">
<tr>
<td>Name</td><td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Mobile</td><td><input type="text" name="mobile" maxlength="10"/></td>
</tr>
<tr>
<td>Address</td><td><input type="text" name="address" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="btn" value="submit"></td>
</tr>
</table>
<input type="button" onclick="myFunction()" name="add" value="Add">
Logout
</form>
</body>
</html>

php uploading files

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.

editing existing image php mysql

I have the following code that displays a given image using php echo id from a mysql table. The php is:
<?php include 'dbc.php'; page_protect();
$id=$_GET['id'];
if(!checkAdmin()) {header("Location: login.php");
exit();
}
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$login_path = #ereg_replace('admin','',dirname($_SERVER['PHP_SELF']));
$path = rtrim($login_path, '/\\');
foreach($_GET as $key => $value) {
$get[$key] = filter($value);
}
foreach($_POST as $key => $value) {
$post[$key] = filter($value);
}
?>
<?php
if($_FILES['photo'])
{
$target = "images/furnishings/";
$target = $target . basename( $_FILES['photo']['name']);
$title = mysql_real_escape_string($_POST['title']);
$pic = "images/furnishings/" .(mysql_real_escape_string($_FILES['photo']['name']));
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
mysql_query("update `furnishings` set `photo`='$pic' WHERE id='$id'") ;
echo "Image updated";
}
else
{
echo "Please select a new image to upload";
}
}
?>
The HTML is:
<form enctype="multipart/form-data" action="editfurnimage.php" method="POST">
<table width="450" border="2" cellpadding="5"class="myaccount">
<tr>
<td width="35%" class="myaccount">Current Image: </td>
<td width="65%"><img src='<?php
mysql_select_db("dbname", $con);
mysql_set_charset('utf8');
$result = mysql_query("SELECT * FROM furnishings WHERE id='$id'");
while($row = mysql_fetch_array($result))
{
echo '' . $row['photo'] . '';
}
mysql_close($con);
?>' style="width:300px; height:300px;"></td>
</tr>
<tr>
<td class="myaccount">New Image: </td>
<td><input type="file" name="photo" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" class="CMSbutton" value="Add" /></td>
</tr>
</table>
</form>
While the coding is adding the new image to the server, the mysql table doesnt seem to be updating with the new image - in fact no changes are being made - when I adjust the line:
mysql_query("update `furnishings` set `photo`='$pic' WHERE id='$id'") ;
to:
mysql_query("update `furnishings` set `photo`='$pic' WHERE id='8'") ;
it works though so assuming the issue is lying with this part of the code but not sure how to correct the code to pull the $id into the php correctly.
Finally, when the script runs I am trying to get the page "editfurnimage.php?id=$id" to reload following the user clicking the Add button - at the moment the page that is returned is "editfurnimage.php" which obviously doesnt show up any data from the table.
Any help much appreciated - and as always feel free to tear my coding apart - still learning!!
Thanks
JD
try to remove your single quotes around $id.
If your id field in the database in an int, then quotes should not be used around it.
EDIT: Missed this one - Where is $_GET['id'] being sent from, because your form sure isn't sending any id in the $_GET scope? Try adding the input with a name of 'id' and a value for it in to your form. also, use $_POST in your php file, not $_GET.
In your php, replace:
$id=$_GET['id'];
With
if(isset($_POST['id'])){
$id=$_POST['id'];
}else{
$id=$_GET['id'];
}
Then in your html add:
<input type="hidden" name="id" value="<?php echo $id; ?>"/>

Categories