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?
Related
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";
SOS! I am trying to build a simple search feature that either creates a new row with the search content or increments the amount of times that particular content has been searched if the row already exists. I tried doing a similar SQL call straight inside of phpMyAdmin but it gave me a #1064 error? ($_POST['search'] is the search content)
<?php
$con=mysqli_connect(...);
$result = mysqli_query($con,"IF EXISTS (SELECT * FROM search WHERE text='" . $_POST['search'] . "')
UPDATE search SET searches=searches+1 WHERE text='" . $_POST['search'] . "'
ELSE
INSERT INTO search (text, searches) VALUES ('" . $_POST['search'] . "', '1')");
echo $result;
?>
Make the "text" column of the "search" table a "unique key". Then you can use this query:
INSERT INTO search (text,searches) VALUES ({$searched_text},1)
ON DUPLICATE KEY UPDATE searches=searches+1;
At first you are doing very wrong thing in your sql.
Please for your sake and sake of application, never never let unfiltered input into your sql query. This can lead to SQL Injection and someone can easily highjack your db.
So, lets fix this first:
$search = mysql_real_escape_string($_POST['search']);
Now when we have fixed it, lets try to do something with it.
I dont know if you have set a key for that table, but i suppose you do, so to escape your conditional try to simply do next thing:
insert into search (searches) values($search) on duplicate key update searches=searches+1
Please let me know how its going.
Kind regards
Vlad
I'm working on a mailbox system for a game on Facebook. I have 2 inputs to a php script, with example input below:
$FriendIDs = "10000001,10002421,10132000,10074794,13523543"
$MailCode = "ReqGem"
and a table with the columns ID, Mailbox.
What I want to be able to do is concatenate whatever was originally in the Mailbox field, with MailCode, for each person in the FriendIDs.
I figured it was something like this, but I couldn't get it to work (my php/sql knowledge is pretty dire!):
mysqli_query($db, "UPDATE Save SET Mailbox = CONCAT(Mailbox,'$MailCode' . '_') WHERE 'id' IN $FriendIDs);
EDIT: I've just realized I need to add a new row if the FriendID isn't already in the table.
I'm guessing I need to start out with INSERT INTO and then use ON DUPLICATE KEY UPDATE, but I can't seem to get it to work. It's a bit trickier since the unique key is in an array, and I can't use WHERE id IN(ArrayOfValues) in an INSERT query.
Any help would be greatly appreciated!
You're close:
$FriendIDs = "10000001,10002421,10132000,10074794,13523543";
$MailCode = "ReqGem";
mysqli_query($db, "UPDATE Save SET Mailbox = CONCAT(Mailbox,'$MailCode' . '_') WHERE `id` IN($FriendIDs));
You just needed the parenthesis for IN() as it is a function.
Don't use single quotes for column names. Use ticks. Single quotes are for strings.
I have a table with 5 columns. ID, name, surname, company & title.
So what I want to do now is to check for duplicate entries during the submitting process, comparing name and surname combination matches. This should then lead to alerting of the duplicate entry and an option to proceed and save it into the database anyway, or cancel the submitting of the content.
Thanks in advance.
You have this option:
setup a conventional index on "(name, surname)"
before each insert, check if the "(name, surname)" combination already exists
if NOT EXISTS, do the insert normaly [here it is up to you to consider the risk that in this 1ms time sb else might have done the same insert]
if EXISTS AND force mode, add the row anyway
if EXISTS AND NOT force mode, proceed to the client according to your specifications
if the client wants to save anyway, repeat operation in force mode.
Here the alternative if you really think this is worth it, is to insert the row anyway and AFTERWARDS check if there were previous rows. If the client wants to keep the record, leave it, otherwise delete it.
rgds
Well here is what I tried, however didn't figure out the optional selection code mentioned in the question yet.
$query = "INSERT INTO phptablo (Name, Surname, Company, Title) VALUES ('$name', '$surname', '$company', '$title')";
$sql = "SELECT Name AND Surname FROM phptablo WHERE Name = '$name' AND Surname= '$surname'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$row = mysql_fetch_array($result);
echo "$sql" . '<br/><br/>';
echo "$result" . '<br/><br/>';
if ($count==0)
{
if (!mysql_query($query))
{
die('Error: ' . mysql_error());
}
echo "Successful Entry!";
}
else
{
echo "Duplicate Entry found!";
}
I'm QUITE NEW to php & MySQL so can't really make that much use of your much appreciated answers. Any chances to add some code that would give me the option to save it or not?
Where I am at right now, the input isn't saved into the database if a duplicate entry is detected, else it is stored right away. If the code I wrote can't really be altered in a way to save duplicates anyway, I could also use some sort of screen showing the duplicates after saving them, so they can be edited, erased etc.
i might be doing some idiot mistake, but i could not figure that out. i have some values coming from html and wanna insert into mysql db. problem is, the very same query does not work in regular php file (that includes other queries), but when i try on an independent php file, it does. here is a sample of the code:
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '".$_POST['Article_Title']."') ";
mysql_query($sql15);
as i mentioned, the very same code works when i just copy this snippet to a new php file, and it works smoothly.. as you see, there are 20+ insert with the same php, because there are 25+ tables, but data is not much. first 14 query and following 7 queries do work by the way.
do you have any ideas?
There are some things to check and do.
Sanitize user input:
"('$article_id', '".mysql_real_escape_string($_POST['Article_Title'])."')";
You might also want to check if the value is what you expect.
Is your $article_id correct for column Article_ID?
Are your table and column names correct?
Check for errors:
$res = mysql_query($sql15);
if (!$res)
echo mysql_errno($link) . ": " . mysql_error($link);
Show us you complete query:
echo $sql15;
First of all i would suggest you to write your insert query like below
$sql15="insert into body SET Article_ID = '$article_id', Article_Title = '".$_POST['Article_Title']."'";
echo $sql15;
mysql_query($sql15);
so that each time when you add new column to database it would be easy for u to change insert query. echo your query and see it in browser. in it seems to o.k then copy it and paste it in SQL section under your phpmyadmin (see you are choosing proper database) and run it. if one row inserted successfully then your query is alright.
I hope this would help you a little.
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '".$_POST['Article_Title']."') ";
mysql_query($sql15) or die(mysql_error());
use like this u will be get the error. then u will be find the issue
I think using mysql_real_escape_string may solve your problem.I also recommend you to store your form data in a string.
$article_title= mysql_real_escape_string($_POST['Article_Title']);
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '$article_title') ";
mysql_query($sql15) or die(mysql_error());