Auto increment wont update - php

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

Related

php image update query, how to update the query

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

Column count doesn't match value count at row 1 when submitting a form

I've been fighting with a bit of code for a week now, not seeing what the heck is wrong...
I have a gaming site I'm trying to build new character sheets for, the form is all done, the action pointing to another page that is strictly the sql for inserting the information into the database. We have good connection, but it is hanging at the second insert statement. The code was working previously, but we had to delete the database and rebuild it, resulting in a rebuild of the insert sql lines.
The first portion of the insert code is:
if($_POST['Submit']=="Submit")
{
$sql="INSERT INTO accounts (log_name,owner,account_type,date_joined) VALUES (\"$_POST[char_name]\",\"$_SESSION[logname]\",\"$_POST[account_type]\",NOW())";
$result = mysql_query($sql)
or die("<p>Couldn't add character.<br/>".mysql_error()." in accounts.<br/>Please send this exact message to <a href='mailto:savvannis#houston-by-night.com'>Savvannis</a> with your character's name.</p>");
echo $result;
echo $_SESSION['logname'];
$sql="INSERT INTO topdata (log_name,char_venue,sub_venue,species,char_name,create_date,gender,age,appage,nature,demeanor,concept,description,web_site,view_pword,sfa) VALUES (\"$_SESSION[logname]\",\"$_POST[char_venue]\",\"$_POST[sub_venue]\",\"$_POST[species]\",\"$_POST[char_name]\",NOW(),\"$_POST[gender]\",\"$_POST[age]\",\"$_POST[appage]\",\"$_POST[nature]\",\"$_POST[demeanor]\",\"$_POST[concept]\",\"$_POST[description]\",\"$_POST[web_site]\"\"$_POST[viewpw]\",\"$_POST[sfa]\")";
$result=mysql_query($sql)
or die ("<p>Could not create character.<br/>".mysql_error()." in topdata.<br/>Please send this exact message to <a href='mailto:savvannis#houston-by-night.com'>Savvannis</a> with your character's name.</p>");
echo $result;
When the information is entered into the form and submit is hit, I get the following:
1
Could not create character.
Column count doesn't match value count at row 1 in topdata.
Please send this exact message to Savvannis with your character's name.
I look at the database and the information is entered into the accounts table, so that statement is working, but it is hanging up on the topdata table. It's not echoing the $_SESSION['logname'] and looking at the database, it's not saving the owner, which should be $_SESSION['logname'], so I'm wondering if that statement is now somehow incorrect??
I can't figure out what the heck is wrong. Any and all help would be greatly appreciated.
You have missed a comma here: \"$_POST[web_site]\"\"$_POST[viewpw]\" in your second insert SQL.
It should be \"$_POST[web_site]\", \"$_POST[viewpw]\"
First off the error message is telling you that there is an unequal number of columns and values in your SQL
Lets have a look at that
INSERT INTO topdata (
log_name,
char_venue,
sub_venue,
species,
char_name,
create_date,
gender,
age,
appage,
nature,
demeanor,
concept,
description,
web_site,
view_pword,
sfa
) VALUES (
\"$_SESSION[logname]\",
\"$_POST[char_venue]\",
\"$_POST[sub_venue]\",
\"$_POST[species]\",
\"$_POST[char_name]\",
NOW(),
\"$_POST[gender]\",
\"$_POST[age]\",
\"$_POST[appage]\",
\"$_POST[nature]\",
\"$_POST[demeanor]\",
\"$_POST[concept]\",
\"$_POST[description]\",
\"$_POST[web_site]\"\"$_POST[viewpw]\",
\"$_POST[sfa]\"
)";
Now by formatting your SQL (which is vulnerable to sql injection) I've noticed a missing comma between web_site and viewpw values

add to a mysql column instead of replacing?

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);

mysql_affected_rows(); does not work for checking if row exists

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

Update a row if ID exists else Insert

This is the code of a .php file. The column "memberid" has a unique index. When a user enters a record with an existing memberid, the record must get updated else a new row is created.
I also want to show an alert box. For test purposes I added like the way below, but it is not firing. No message is displayed.
I also want to know whether it is the right approach to handle insert/update automatically?
<META http-equiv="refresh" content="2; URL=socialprofile.html">
<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once("../Lib/dbaccess.php");
//Retrieve values from Input Form
$CandidateID = $_POST["inCandidate"];
$SocialProfile = $_POST["inActivities"];
$InsertQuery = "INSERT INTO candidate_db_social (memberid, socialactivities, lastupdated) VALUES (".$CandidateID.",'".$SocialProfile."',now())";
$UpdateQuery = "UPDATE candidate_db_social SET socialactivities='".$SocialProfile."', lastupdated=now() WHERE memberid=".$CandidateID;
try
{
$Result = dbaccess::InsertRecord($InsertQuery);
}
catch(exception $ex)
{
$Result = dbaccess::InsertRecord($UpdateQuery);
echo "<script type='text/javascript'>alert('".$ex."');</script>";
}
?>
You should use the MySQL ON DUPLICATE KEY clause:
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Also see REPLACE:
http://dev.mysql.com/doc/refman/5.0/en/replace.html
See the MySQL REPLACE keyword. It works exactly like INSERT, but overwrites existing records based on primary key. Read up on the details though, because it's not exactly equivalent to trying an INSERT, followed by an UPDATE.
INSERT ... ON DUPLICATE might be what you need instead. Situations with triggers or foreign keys come to mind. Longer syntax however :)
REPLACE INTO candidate_db_social (memberid, socialactivities, lastupdated) VALUES (".$CandidateID.",'".$SocialProfile."',now())";
you can use the INSERT ... ON DUPLICATE KEY UPDATE syntax, as in:
insert into t values ('a', 'b', 'c') on duplicate key
update a='a', b='b', c='c'
use mysql
INSERT INTO table VALUES()
ON duplicate KEY UPDATE ..;
example :
http://www.mysqlperformanceblog.com/2006/05/29/insert-on-duplicate-key-update-and-summary-counters/
I usually just check for the existence of a record ID value from either the $_POST or $_GET array (depending on the situation). If a value exists and is numeric, attempt to UPDATE the row with the corresponding ID; if not perform an INSERT query.

Categories