Exampe list view:
Example of edit view:
$imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));
$sql = "INSERT INTO imgexam
(image, name)
VALUES
('{$imgData}', '{$_FILES['userfile']['name']}');";
How to change the query, so it will update the current image instead of inserting a new one?
So what you have to do to update it to the new image is the following steps:
Remove old image Upload
new image Update the row in the database to
the name of the new image
How to remove old image using PHP:
unlink('directory/images/'.$image);
You might need to do a selection from the database to get the right image name.
How to upload new image using PHP:
Read this page for more informations on uploading files
Then after uploading the new image, you need to change the row in the database.
How to change the row in the database
$sql = "UPDATE FROM `table` SET `imagename` = '$newimagename' WHERE `imagename` = $oldimagename";
$query = mysql_query($sql) or die(mysql_error());
Thats is the steps you need. Ask if you have problems.
The SQL query you're looking for to update a record would be similar to this:
UPDATE imgexam SET image = ? WHERE name = ?;
If you have duplicate names, you'll want to retrieve the ID for the record and use that in the WHERE clause. You can get the ID with a method like PDO::lastInsertId() or by querying for it.
What you may also be looking for is sometimes called an UPSERT operation. This means I want to UPDATE or INSERT. MySQL provides an ON DUPLICATE KEY clause. Let's assume ID is your primary key for this table.
Change your query to read
INSERT INTO
imgexam (id, image, name)
VALUES (1, '{$imageData}', '{$_FILES['userfile']['name']}')
ON DUPLICATE KEY UPDATE
image = '{$imageData}';
Update query for BLOB things:
mysql_escape_string() just treats the string as raw bytes, and adds escaping where it believes it's appropriate.
$query = "UPDATE mytable SET blobthing = '" .mysql_escape_string($varblobthing) .
"' WHERE id=2";
Related
I want to add an extra value to a mysql table column, e.g:
the field 'photos' already has an image name in, but i want to add another image name into the field using php.
I thought INSERT would just add it in on top but it seems to replace the existing image name. I want to avoid selecting the current field values, adding the new value and re-inserting if possible.
thanks!
code:
php:
$query = "INSERT INTO `listings-rent` (photos) VALUES ('$fileName') WHERE id = '$insertID'";
mysqli_query($mysqli, $query);
the problem is this replaces the existing value in the 'photos' column, rather than adding to it
It is highly discouraged, to keep multiple values in the same column. But it is, of course possible.
UPDATE `photos` SET imagename = CONCAT(imagename, ",", $second_name) WHERE id=$insertID'
You will then use explode in PHP to get an array of strings like:
array("image1.jpg", "image2.jpg")
You insert with a WHERE statement. This will not work.
try:
$query = "INSERT INTO `listings-rent` (photos,id) VALUES ('$fileName', $insertID)";
mysqli_query($mysqli, $query);
I currently have a script to upload photos, at the moment it uploads multiple images adding a new row to the mySQL database each time a new one is created. However I want the user to only be able to upload 1 image maximum.
I have therefore changed the register script to insert a row straight in to the database with a default image for each new user that registers.
The image upload script once logged in currently uses the below line to put the data in to the database
$sql2= "INSERT INTO `profile_photo` (`profile_id`,`title`,`size`,`type`,`reference`)
VALUES ('".$_SESSION['id']."','$title','$size','$type','$pic'); ";
However this is not how I want this to work; I believe the resolve would be to change this to an UPDATE row.
This is causing an issue when I change the line, I believe I have not quite grasped the concept of updating rows in mySQL.
Please can you advise?
$sql2=
"INSERT INTO `profile_photo` (`profile_id`,`title`,`size`,`type`,`reference`)
VALUES ('".$_SESSION['id']."','$title','$size','$type','$pic')
ON DUPLICATE KEY UPDATE title = VALUES(title), size = VALUES(size), type = VALUES(type), reference = VALUES(reference)";
Would solve this if the profile_id column got the index unique.
Behavior
This will INSERT all the data in a new row if the profile_id isn't already added. If it is, it will run an UPDATE instead.
However your code is pretty much begging for mysql injections. Do read up on this before it ruins your site.
Bobby tables, for your consideration.
Read up on DUPLICATE KEY here.
Assuming that profile_id is your unique key:
$sql2= "
INSERT INTO
`profile_photo` (`profile_id`,`title`,`size`,`type`,`reference`)
VALUES ('".$_SESSION['id']."','$title','$size','$type','$pic')
on duplicate key update set title='$title', size='$size', type='$type', reference='$reference'; ";
You can also use the replace into:
$sql2= "
Replace into
`profile_photo` (`profile_id`,`title`,`size`,`type`,`reference`)
VALUES ('".$_SESSION['id']."','$title','$size','$type','$pic')";
I think this question misses some information.
You might want to look into the REPLACE INTO statement
Or look up the MySQL UPDATE reference manual page
What you need is to execute the UPDATE sql statement:
$sql3= "UPDATE `profile_photo` SET `title`='" . mysql_real_escale_string($title) .
"', `size`='" . mysql_real_escape_string($size) .
"', `type`='" . mysql_real_escape_string($type) .
"', `reference`='" . mysql_real_escape_string($pic) .
"' WHERE `profile_id`=" . $_SESSION['id'];
Maybe the solution is Replace?
just created a form that saves the filename into an SQL database.
The thing is that when I ad the ID column(Auto increment) into the SQLDatabase the form stops to save my filename, but as soon I delete the ID row, it begins to save.
Dont know whats the problem.
this is some of my code
<?php
if(isset($_FILES['file_name'])) {
$file_name = mysql_real_escape_string($_FILES['file_name']['name']);
//Writes the information to the database
mysql_query("INSERT INTO `files` VALUES ('$file_name')") ;
}
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM files") or die(mysql_error());
//Puts it into an array
?>
And my database has two columns file_id and file_name
but as I just wrote, the file_id wont work =/
Any ideas ?
I think you need to change your SQL query to this:
mysql_query("INSERT INTO `files` (`file_name`) VALUES ('$file_name')") ;
With more than one column, you need to name which column you want the $file_name string to be saved in if you're not going to enumerate every column in the table. Then your auto-increment should work fine.
In fact, the problem isn't with auto-increment, it's with your SQL syntax. You should check your queries for errors by saving the return value from mysql_query and checking if it returned false. If it did, call mysql_error to determine the error message.
Since ID is auto_inc, you don't need to include it in your script anywhere.
I think the problem is because you don't specify in your query what fields to put the values in.
Change this:
mysql_query("INSERT INTO `files` VALUES ('$file_name')") ;
To something like this
mysql_query("INSERT INTO `files` (`YOURFIELD`) VALUES ('$file_name')") ;
I have a database field image URL in which there are image names like image-0073 but i need to create a URL like www.xxxxx.com what i already did with the following code
if (isset($result2['img_name'])) {
$result2['img_name'] = 'http://www.xxxxxx.com/' . $result2['img_name'];
But now i have to replace the name of image image-0073 with new name www.xxxxx.comimage-0073 in the field image URL but don't know how to update that specific field.
Use CONCAT function
like below :
update tablename set imageURL=CONCAT("www.xxxxx.com',imageURL)
Please add conditions and do changes according to your requirments.
update table set img_name = concat('http://www.xxxxxx.com/',img_name) where some_field=condition
note that if you are going to update every field in the table with no condition, it will make no sense.
I am also have no idea why do you say you want to empty the field.
You can try:
UPDATE table_name SET field_name = $newImageUrl WHERE img_name = $result2['img_name'];
i am using mysql_affected_rows() to check if i have to enter new record or update existing, but the problem is if the user tries to enter exactly same data as record which already exists it runs insert into.
$result = mysql_query("update Data set Score='$score',Comment='$_POST[Comments]' where Date='$_POST[forDay_3]-$_POST[forDay_1]-$_POST[forDay_2]' AND User='$_POST[UserID]';");
$last = mysql_affected_rows();
if ($last==0) {
$result1 = mysql_query("INSERT INTO Data (User,Date,Score,Comment) VALUES ('$_POST[UserID]','$_POST[forDay_3]-$_POST[forDay_1]-$_POST[forDay_2]','$score','$_POST[Comments]')");
what should i do to avoid redundant entries
You could parse mysql_info() output (but the solution itself will be affected by race condition issue)
You could create unique key User + Date and end up with a single query using ON DUPLICATE KEY UPDATE syntax:
INSERT INTO `Data` (User,Date,Score,Comment)
('$_POST[UserID]','$_POST[forDay_3]-$_POST[forDay_1]-$_POST[forDay_2]','$score','$_POST[Comments]')
ON DUPLICATE KEY UPDATE Score='$score',Comment='$_POST[Comments]'
some solutions:
add another query to see if data exists, and then decide if you want to do some action (update/delete) or nothing.
add a 'modified' column with type "TIMESTAMP" and make it on update - CURRENT_TIMESTAMP
i'd go with first option.
btw, you should escape your post data (mysql_real_escape_string) to prevent injects or malformed query string
You may get the number of affected rows with FOUND_ROWS() instead of mysql_affected_rows(). The latter counts the not modified rows as well.
$result = mysql_query("update Data set Score='$score',Comment='$_POST[Comments]' where Date='$_POST[forDay_3]-$_POST[forDay_1]-$_POST[forDay_2]' AND User='$_POST[UserID]';");
$last = mysql_query("SELECT ROW_COUNT();");
$last = mysql_fetch_array($last);
...
Reference: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_row-count