phpmysql update set while uploading image - php

I am really struggling trying to get something very simple achieved.
Essentially, I have an images table called galleryimages and a location on the server where images are stored. What I am trying to do is overwrite the source field for a given category in the table while the upload is going through.
My code will add the new image to the server, but not update the MySQL table for some reason (I can however add new lines to it although I want to keep the existing data in the table and simply change the "photo" field which locates the image).
My PHP is:
<?php include 'dbc.php'; page_protect();
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 = "galleries/test/";
$target = $target . basename( $_FILES['photo']['name']);
$title = mysql_real_escape_string($_POST['title']);
$pic = "galleries/test/" .(mysql_real_escape_string($_FILES['photo']['name']));
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
mysql_query("update `galleryimages` set (`title`, `photo`) VALUES ('$title', '$pic')") ;
echo "Success";
}
else
{
echo "Failure";
}
}
?>
And the HTML is:
```html
</head>
<body>
<form enctype="multipart/form-data" action="addgallery1.php" method="POST">
<table width="100%" border="2" cellpadding="5"class="myaccount">
<tr>
<td>Category: </td>
<td><select name="title" id="select8">
<option value="Landscape Pots">Landscape Pots</option>
</select></td>
</tr>
<tr>
<td>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>
</body>
</html>
Now I am fairly sure the problem exists in the line:
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
mysql_query("update `galleryimages` set (`title`, `photo`) VALUES ('$title', '$pic')") ;
echo "Success";
}
but need some help to determine if this is indeed the case - and if so how I can get it to update the MySQL table - at the moment the PHP echoes Success but does not make any update to the "photo" column in MySQL.
Hope this makes sense and one of you coding geniuses can help me resolve this - its taken me hours of trial and error but still cant get it working!!!
thanks in advance to any and all help
JD

some thing wrong here
mysql_query("update `galleryimages` set (`title`, `photo`) VALUES ('$title', '$pic')") ;
it should be like
mysql_query("update `galleryimages` set `title`='$title', `photo`= '$pic'") ;
more info here: http://dev.mysql.com/doc/refman/5.0/en/update.html

Your MySQL query is wrong:
update `galleryimages` set `title`='$title', `photo`='$pic'
But be warned: This will update ALL rows in this table! You should add a WHERE clause to update one specific row.

Related

Saving multiple form data to mysql using php

I have a table form which has a add new row button which upon clicked adds a new row to the table. I am trying to save all the rows in MySQL on clicking save button.
The code I wrote saves only one row no matter how many row I add. Could someone please tell my what am I doing wrong.
I searched Google but couldn't get anywhere.
Here are my codes:
save.php
<?php
include('connection.php');
if(isset($_POST['submit'])){
$row_data = array();
foreach($_POST['category'] as $row=>$category){
$category = mysql_real_escape_string($category);
$itemName = mysql_real_escape_string($_POST['itemName'][$row]);
$brand = mysql_real_escape_string($_POST['brand'][$row]);
$model = mysql_real_escape_string($_POST['model'][$row]);
$sellingPrice = mysql_real_escape_string($_POST['sellingPrice'][$row]);
$row_data[] = "('$category','$itemName','$brand','$model','$sellingPrice')";
}
}
if(!empty($row_data)){
$insert_query = mysql_query("INSERT INTO sale(Category,ItemName,Brand,Model,SellingPrice) VALUES".implode(',', $row_data));
if(!$insert_query){
echo "Error: " . mysql_error();
}else{
echo "Data Saved Successfully";
}
}
?>
and this is my html form
<form name="form1" id="myForm" action="saveSale.php" method="post">
<tr class="cloneme">
<td><input type="text" name="category[]"></td>
<td><input type="text" name="itemName[]"></td>
<td><input type="text" name="brand[]"></td>
<td><input type="text" name="model[]"></td>
<td><input type="text" name="sellingPrice[]"></td>
</tr>
</tbody>
</table>
</div>
<div class="eventButtons">
<input type="submit" name="submit" id="submit" value="Save">
<input type="reset" name="reset" id="reset" value="Clear" class="btn">
</div>
</form>
You are inserting data outside the for loop so it inserts only the last row or data.. What you have to do is to place insert query within foreach or for loop
if(isset($_POST['submit'])){
$row_data = array();
for($i = 0 ; $i < count($_POST['category']);$i++){
$category = mysql_real_escape_string($_POST[$i]['category']);
$itemName = mysql_real_escape_string($_POST[$i]['itemName']);
$brand = mysql_real_escape_string($_POST[$i]['brand']);
$model = mysql_real_escape_string($_POST[$i]['model']);
$sellingPrice = mysql_real_escape_string($_POST[$i]['sellingPrice']);
$insert_query = mysql_query("INSERT INTO sale(Category,ItemName,Brand,Model,SellingPrice) VALUES ('$category','$itemName','$brand','$model','$sellingPrice')");
if(!$insert_query){
echo "Error: " . mysql_error();
}else{
echo "Data Saved Successfully";
}
}
}
As I dont have enough reputation I am adding my comment as answer.
Your code is fine. It should work. There might be problem while you are cloning the row, may be it is not getting added under the form tag. You can verify it by dumping the $row_data variable.
Please share your javascript code which makes clone of the row, it will help us to solve your problem.
You need to run your query in for loop by counting the array value using count($_POST['category'])
if(isset($_POST['submit'])){
$row_data = array();
for($i= 0; $i <count($_POST['category']);$i++){
$category = mysql_real_escape_string($_POST[$i]['category']);
$itemName = mysql_real_escape_string($_POST[$i]['itemName']);
$brand = mysql_real_escape_string($_POST[$i]['brand']);
$model = mysql_real_escape_string($_POST[$i]['model']);
$sellingPrice = mysql_real_escape_string($_POST[$i]['sellingPrice']);
$insert_query = mysql_query("INSERT INTO sale(Category,ItemName,Brand,Model,SellingPrice) VALUES ('$category','$itemName','$brand','$model','$sellingPrice')");
if(!$insert_query){
echo "Error: " . mysql_error();
}else{
echo "Data Saved Successfully";
}
}
}

How to edit, delete and add in php mysql without jquery or java script?

I am trying to delete , edit and add new recodes on the same page but it seems am failing to make it work .And I do not want to do it using ajax jquery or java script but only php .I need some help please below are my code :
<?php
include_once('con.php');
$strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL);
echo "<table border='1' ><tr bgcolor='#eeeeee'><td>Name</td> <td colspan='2'>Action</td></tr>";
while($row = mysql_fetch_assoc($rs))
{
$film_id = $row['film_id'];
$name = $row['name'];
$hometeam= mysql_real_escape_string($name);
echo "<tr bgcolor='#eeeee'><td>$name</td> <td><a href='index.php?film_id=$film_id' name ='edit'>Edit</a></td><td><a href='index.php?film_id=$film_id' name ='delete'>Delete</a></td></tr>";
}
?>
<?php
$strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL);
$row = mysql_fetch_assoc($rs);
$film_id= $row['film_id'];
$name = $row['name'];
$name = mysql_real_escape_string($name);
$film_id= $_GET['film_id'];
?>
<?php
if(isset($_POST['edit'])){
?>
<table>
<form action="index.php" method="post">
<tr>
<td>
Name
</td>
<td>
<input type = "text" name = "name" value="<?php echo $name;?>">
</td>
</tr>
<input name="film_id" type="hidden" id="film_id" value="<?php echo $film_id; ?>">
<tr>
<td>
<input type = "submit" name = "submit" value="update">
</td>
</tr>
<?php
$name = (isset($_POST['name']))? trim($_POST['name']): '';
$film_id = $_POST['film_id'];
$sql = "UPDATE filmsbox SET name='$name'
WHERE film_id ='$film_id'";
$result = mysql_query($sql);
if($result)
{
echo "Success";
}
else
{
echo "Error";
}
}
?>
<?php
/*Delete section*/
if(isset($_POST['delete']))
{
$film_id = $_GET['film_id'];
$delete = "DELETE FROM filmsbox WHERE film_id = '$film_id'";
$result = mysql_query($delete);
if($result)
{
echo "Record deleted successfuly ";
}
else
{
echo "No data deleted";
}
}
?>
Couple of pointers:
You only need to escape values before they go into the database, not when they come out and are used in HTML i.e $hometeam = mysql_real_escape_string($name);
You are pulling the same query from the database twice in quick succession which is not needed. You can remove one of the 2 $strSQL = "SELECT film_id, name
from
filmsbox";
$rs = mysql_query($strSQL); sections from the top of your code
You need to run any update/delete queries on the data before you then do your select query to pull out the records for the page, otherwise your changes will not be shown
You should be escaping the values for your update and delete queries to prevent SQL injection
Edit:
To reload the page in an edit mode, you need to change the link URL in the table to something like
<a href='index.php?film_id=$film_id&edit=1' name ='edit'>Edit</a>
Then your edit block needs to be
if ($_GET['edit']) {
I want to be clear this is not in any way a secure method of editing values, as anyone can put ?edit=1 on the url and get to the form

Newbie: Building an employee directory with scripts for add/edit/search/delete. Errors

I am building an employee directory that has 3 simple forms. The first adds records, the second searches for records, the third searches then deletes records.I want to display all the records on the same page, and then when a search is done, just display those records that fit the search keyword.
I have built the DB and the Table correctly. The first form adds records to the DB successfully. Before I make the search and delete forms work correctly I am trying to get the records to display. They are not displaying. Sometimes I can get my html table to display, but none of the records appear. However, I know that the records exist because I can see them in MyAdmin.
I am getting this error right now, but my errors are changing by the moment as I try new things: Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in C:\xampp\htdocs\Employees.php on line 84
I would love some help to do the following:
1. Help me understand why I am getting this error.
2. Help me understand how to display my records (I've done this successfully before, but with a simpler task).
I know this code is unfinished. I am building it piece by piece and trying to get each individual piece to function before I add the next. Thanks!
<html>
<body>
<?php error_reporting (E_ALL ^ E_NOTICE);
$keyword = $_GET['keyword']; ?>
<?php
$con = mysql_connect("localhost", "employees", "employeepw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("employees", $con);
mysql_query("INSERT INTO employeeinfo (firstname, lastname, phone, email, department, position)
VALUES ('$_POST[firstname]', '$_POST[lastname]', '$_POST[phone]', '$_POST[email]', '$_POST[department]', '$_POST[position]')");
mysql_query($sql,$con);
function buildQuery() {
$keyword = $_GET['keyword'];
$sql = "SELECT * from employeeinfo WHERE
(
firstname LIKE '%$keyword%'
OR
lastname LIKE '%$keyword%'
OR
phone LIKE '%$keyword%'
OR
email LIKE '%$keyword%'
OR
department LIKE '%$keyword%'
OR
position LIKE '%$keyword%'
)";
return $sql;
} ?>
<form action="Employees.php" method="post">
<fieldset>
<legend>Submit Employee Info</legend>
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Phone: <input type="text" name="phone" />
Email: <input type="text" name="email" />
Department: <input type="text" name="department" />
Position: <input type="text" name="position" />
<input type=submit name=submit value=Submit />
</fieldset>
</form>
<form action="Employees.php" method=get>
<fieldset>
<legend>Search Employee Info</legend>
<label for="keyword">Enter Keyword</label>
<input id="keyword" name="keyword" value="<?php echo "$keyword"; ?>" />
<input type=submit name=submit value=Search />
</fieldset>
</form>
<form action="Employees.php" method=get>
<fieldset>
<legend>Delete Employee Info</legend>
<label for="keyword">Enter Keyword</label>
<input id="keyword" name="keyword" value="<?php echo "$keyword"; ?>" />
<input type=submit name=submit value=Delete />
</fieldset>
</form>
<?
function getRecords()
{
$sql = buildQuery();
$resource = mysql_query($sql);
}
while($row = mysql_fetch_array($resource)) { // The error is for this row
$results[] = $row;
}
return $results;
$records = getRecords(); {
foreach ($records as $record) {
}?>
<table>
<tbody>
<table border='1'>
<tr>
<td><?= $row['firstname']; ?></td>
<td><?= $row['lastname']; ?></td>
<td><?= $row['phone']; ?></td>
<td><?= $row['email']; ?></td>
<td><?= $row['department']; ?></td>
<td><?= $row['position']; ?></td>
<td>Return to Search</td>
</tr>
<? } ?>
</tbody>
</table>
</body>
</html>
You aren't getting any rows back. Try changing this
function getRecords()
{
$sql = buildQuery();
$resource = mysql_query($sql);
}
to
function getRecords()
{
$sql = buildQuery();
echo $sql;
exit();
$resource = mysql_query($sql);
}
this will output the SQL you are querying against the database. If it is not immediately apparent, copy and run this query against your database. See if any rows come back. If not then thats your problem!
Also you can use "echo mysql_error();" to get the text of the last error mysql threw.
EXAMPLE:
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
Your mysql query is not going through, or it is retuning 0 rows.
Try to put this
if(!$resource){
echo mysql_error();
echo ' <br>Query: .$sql;
}
statement directly after $resource = mysql_query($sql);
and see what it outputs. Also, make sure error reporting is turned on.
I edited my answer on your post yesterday, you might want to look at it; it may give you some ideas for a different approach.
The link is here:
Fatal error: Call to undefined function getRecords() in C:\xampp\htdocs\Employees.php on line 101
Maybe.. just maybe there is some problem with your code..
function getRecords()
{
$sql = buildQuery();
$resource = mysql_query($sql);
}
while($row = mysql_fetch_array($resource)) { // The error is for this row
$results[] = $row;
}
return $results;
my guess is that your above code should be something like this
function getRecords()
{
$sql = buildQuery();
$resource = mysql_query($sql);
$results = array();
if($resource != null)
{
while($row = mysql_fetch_array($resource))
{
$results[] = $row;
}
}
return $results;
}
Hope it helps :)
Please never do such thing:
mysql_query("INSERT INTO employeeinfo (firstname, lastname, phone, email, department, position) VALUES ('$_POST[firstname]', '$_POST[lastname]', '$_POST[phone]', '$_POST[email]', '$_POST[department]', '$_POST[position]')");
This will produce a HUGE hole in your site security called sql-injection.
You should always check any data gained from user.
The simple example of how it should be:
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$phone = mysql_real_escape_string($_POST['phone']);
$email = mysql_real_escape_string($_POST['email']);
$department = mysql_real_escape_string($_POST['department']);
$position = mysql_real_escape_string($_POST['position']);
mysql_query("INSERT INTO employeeinfo (firstname, lastname, phone, email, department, position)
VALUES ('{$firstname}', '{$lastname}', '{$phone}', '{$email}', '{$department}', '{$position}')");
For more info read: http://php.net/manual/en/mysqli.real-escape-string.php
I think you should find a good book for novices in PHP and read at least from time to time it.
It will help you understand what you writing and how to make it better.
The first book that i googled for this purpose - http://www.amazon.com/Learning-MySQL-JavaScript-Step-Step/dp/0596157134/

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; ?>"/>

'Edit' function for forum posts and such

I was looking online for a script that demonstrates how I would go about making it possible for users on my site able to edit fields and such, but I could not find anything about it. So I was wondering if someone could explain to me how it works or just demonstrate with a script? To make it clear, I want users to be able to edit stuff that they've submitted by simply clicking 'edit' and pressing a button to update whatever it was they changed.
Edit: I forgot to mention that what's been changed should update a table in a MySQL database.
You need 2 PHP files to do this. You could use a single file but the concept is easier to explain this way.
A form that will load the database content into the fields where users can then edit the values and then submit them for change by pressing a button once done.
A file that receives the changed information and updates the database.
Here is a code example for the first file:
<?php
// connect to SQL
$dbcnx = #mysql_connect("localhost", "db_name", "password");
if (!$dbcnx) {
echo( "<P>Unable to connect to the database server at this time.</P>" );
exit();
}
// connect to database
$dbcon = #mysql_select_db("db_table", $dbcnx);
if (!$dbcon) {
echo( "<P>Unable to locate DB table at this time.</P>" );
exit();
}
#data preparation for the query
$id = intval($_GET["id"]);
# selects title and description fields from database
$sql = "SELECT * FROM table_name WHERE id=$id";
$result = mysql_query($sql) or die(mysql_error());
# retrieved by using $row['col_name']
$row = mysql_fetch_array($result);
?>
<h3>Edit</h3>
<form action="save_edit.php" enctype="multipart/form-data" method="post" name="myForm" />
<table>
<tr>
<td><b>Title</b></td>
<td><input type="text" size="70" maxlength="100" name="title" value="<?php echo $row['title'] ?>"></td>
</tr>
<tr>
<td><b>Description</b></td>
<td><textarea cols="80" rows="18" name="description"><?php echo $row['description']; ?></textarea></td>
</tr>
</table>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input name="enter" type="submit" value="Edit">
</form>
<?php
mysql_close($dbcnx);
?>
And here is an example of code for the second file where it receives the changes made by the user and updates the database.
<?php
// connect to SQL
$dbcnx = #mysql_connect("localhost", "db_name", "password");
if (!$dbcnx) {
echo( "<P>Unable to connect to the database server at this time.</P>" );
exit();
}
// connect to database
$dbcon = #mysql_select_db("db_table", $dbcnx);
if (!$dbcon) {
echo( "<P>Unable to locate DB table at this time.</P>" );
exit();
}
#data preparation for the query
$id = intval($_POST["id"]);
foreach ($_POST as $key => $value) $_POST[$key] = mysql_real_escape_string($value);
$sql = "UPDATE table_name SET
title='$_POST[title]',
description='$_POST[description]',
WHERE id=$id";
if (!mysql_query($sql,$dbcnx)) {
die('Error: ' . mysql_error());
}
mysql_close($dbcnx);
header ("location: http://www.domain.com/url_to_go_to_after_update");
?>
If you just need an idea how to create a basic edit form in PhP, that's easy enough. When they click the edit button take them to a new form. Pull the content from the database, using whatever database accessing api you are, and then initialize the field with it. For example, where $content has the content of the field:
echo '<textarea name="content">'.htmlspecialchars($content).'</textarea>';
When they submit the form, take whats now in the field and use it to update the table. It's the same as the original insert script, except that you use update statements instead of insert.
I'm not sure I understood what you said. If you want a way to edit things in place, you can use this jQuery plugin: Jeditable (with Ajax).
To extend Daniel's code a bit
<?php
$filename = "file.txt";
if ($_SERVER['REQUEST_METHOD'] == 'POST']) {
file_put_contents($filename, $_POST['content']);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
$content = htmlspecialchars(file_get_contents($filename));
?>
<form method="POST">
<textarea name="content"><?php echo $content?></textarea><br>
<input type="submit">
</form>

Categories