"REPLACE INTO" versus INSERT [IF] - php

Alright, I've got a question, not really an issue.
I've got a table in my database, fairly small, only 3 columns but potential to grow. I've got two solutions to my problem, but not sure why to use one or the other.
I've got a piece of data, which might or might not already be in the database. Two ways to solve this. I've got the unique ID, so it is easy to check.
Check if the records exists in the database, and if not, INSERT INTO database
Use REPLACE INTO, because I've got the ID already.
My question now is. Which one is better to use. What are the pros and cons in using either of the 2 results. Or is there a better result?
A note, the data is exactly the same, so there is no chance the record gets updated with a newer value. Thus the REPLACE INTO will insert data which is already there.

REPLACE INTO is not recommended here - you don't really need to replace anything. It does DELETE followed by INSERT, with all the consequences. For example all indexes have to be updated, which leads to unnecessary work and index fragmenting if you use it frequently.
On the other hand there is ON DUPLICATE KEY UPDATE, which is used mainly for counters, but you are not updating your row with increments or any other value changes, so you would have to use weird syntax like SET id=id or something similar.
Checking if the record exists in the database would be the best solution for you, but instead of using another query let mysql do that check for you and use:
`INSERT IGNORE INTO ...`
This way if you try to insert any row with duplicated unique or primary key it simply won't be inserted without generating any error. Note the side effect of possibly missing other error messages, but if you know exactly what you insert you should be fine.

Related

Check input data by MySQL schema or PHP?

Suppose I'd like to check whether a comment is duplicated or not.
I have two options:
1) Create a query to database and check for it:
select * from comments where content=$santized_content and post_id=$id
2) Create a unique index for comment and post_id and catch MySQL error.
It's important for my complex and busy app to decrease number of queries to database as much as possible. However the first option is more usual and readable.
You can generalize this question to other situations.
MySQL is definitely faster than PHP. I would always prefer using a failing INSERT or a REPLACE against a suitable key than checking in PHP.
The only exception would probably be that your key becomes very complex which will obviously create overhead on MySQL for all queries run against that table. However, there isn't a one-size-fits-all answer to the question what would be too complex to be worthwhile doing. It's largely a matter of real life testing.
i prefer number 2 ,
your PHP script will less code.
It will check automatically whenever comment is duplicate or not.
then this is the function of UNIQUE.

PHP MySQL Management

Sorry guys, I'm no master of MySQL and I've only just begun learning this but the first thing getting me frustrated right now is adding a field that is a "Longtext" and it automatically goes PRIMARY and INDEXED and also UNIQUE.
That field I'm talking about is for storing huge amount of characters, basically it is where I plan to store 1 page of texts which is why I need it to be "Longtext". Problem is no matter what I do I can't remove Unique or Indexed or Primary from fields that are "Longtext". I do not want to remove it through queries, I am trying to remove it through PHPMyAdmin since I don't want to do the SQL query for this task only. I keep clicking on the fields and clicking Index or Primary or Unique but it never changes, I'm getting so frustrated :(
Sounds like the problem is with PHPMyAdmin, rather than MySQL, because what you describe does not sound like any behavior of MySQL. (To find out if it's a MySQL problem, we'd really need to see the actual SQL statements being run, what is recorded in the information_schema tables/views, etc.)
I understand you don't want to run the SQL statements that are actually required by MySQL.
It sounds as if the developers of PHPMyAdmin didn't want to run them either.

PHP memcached update result

I'm about to implement a memcached class which can be extended by our database class. However i have looked at many different ways of doing this.
My First question was, what is the point in the Memcached::set() as it seems to replace the value of the key. Does this not defeat the object of caching your results?
My Second question was, technically speaking what is the fastest/best way to update the value of a key without checking the results every time the query is executed. If this happens, the results been retreived would have to be checked constantly so there would be no point in caching as the results would constantly be connecting to the mysql database.
Lastly, What is the best way of creating a key? most people recommend using MD5 however using MD5 on a PDO query would be the same regardless.
I.E.
$key = MD5("SELECT * FROM test WHERE category=?");
the category could produce many different results however the key would be constantly replaced. Is there a best practice for this?
You set a cache entry when you had to read the database, so that next time, you don't have to read the database first. You'd check the cache, and if it was not there, or otherwise out of date, then you fall back to the database read, and reset the key.
As for a key name, it depends very much on the expected values of the category. If if was a simple integer, or string, I'd use a key like test.category:99 or test.category:car. If it was likely to be more, it may be useful to encode it, so there were no spaces in it (say, urlencode).
Finally, if it were any more complex than that - test:category:{MD5(category)}.
Since the key is only a reference to the data and you'll never be using it in any kind of SQL query, putting the value in there is not generally going to be a security issue.
Since you control when the cache is set, if the underlying database entry is changed, it's simple to also update the cache with the new data at the same time - you just have to use the same key.

Can INSERT be used as a way to update a database instead of using UPDATE?

I am having an issue with an update command. It's not as if the code is written wrong; I've had three people look at it and not come up with a solid answer of why the code is not working. So in lieu of getting the code to work, is it possible to use INSERT to replace the data in the database instead of using UPDATE?
No. Insert will only create a new row.
Well … you could perform a delete followed by an insert, but that way lies madness.
For MySQL, there's REPLACE that deletes possible existing row and inserts (mysql doc) or, equivalaent syntax INSERT ... ON DUPLICATE KEY UPDATE (mysql doc).
For some other databases, there's MERGE - Oracle, MS SQL
Anyway, these are good to know of, but you'd rather fix the UPDATE in the first place.
You would have to insert a new row, check that has inserted row worked and then delete the original, this will cause you all sorts of problem with unique keys.
Post your code and the error you're getting someone here might be able to spot something that has been missed.

MySQL query is creating a duplicate row

I have never encountered an error like this before. I was using prepared statements when it stared and have tried everything to correct the problem including stripping the form down to it's bare components.
The following code, when executed, is creating a duplicate row.
$sql = "INSERT INTO inventory
VALUES ('','$stocknum','$year','$make','$model','$price','$body','$mile','$engine','$trans',
'$drive','$doors','$fuel','$vin','$des','$featured','$sale','$features','$safety','$airbags','$power',
'$exterior','$interior','','','','','')";
$insert = mysql_query($sql,$connection) or die(mysql_error());
$name = mysql_insert_id();
I can't wrap my head around why it would do this.
I had the same problem in a project while using and orm library to access to the database. Also tried tested with mysql directly
After almost one day testing in multiple browsers and getting diferente results, i've found out that the extensions that i used (Webug) for Chrome caused tha recall to the page. After disabling the extension, it worked
I've tested some extensions that caused that problem... In chrome: Webug.
Hope it helps
The insert statement is possibly getting called twice. Did you add logging to make sure this code is only running once? And did you search to make sure there's no other code to add inventory records anywhere else?
How many columns are in the inventory table? Is the second row an exact duplicate of the first? I don't know PHP's DB interface but I could envision a bug where, if you give it more fields than there are columns, it attempts to create multiple rows.
EDIT: A little research on the MySQL documentation finds:
INSERT statements that use VALUES
syntax can insert multiple rows. To do
this, include multiple lists of column
values, each enclosed within
parentheses and separated by commas.
Example:
INSERT INTO tbl_name (a,b,c)
VALUES(1,2,3),(4,5,6),(7,8,9);
The values list for each row must be
enclosed within parentheses. The
following statement is illegal because
the number of values in the list does
not match the number of column names:
INSERT INTO tbl_name (a,b,c)
VALUES(1,2,3,4,5,6,7,8,9);
Depending on the contents of your variables and how the PHP/MySQL driver handles those variables (direct text substition or ? placeholders) the statement being executed may not look like you expect. Try displaying the value of $sql before you execute it.
When you query the table afterwards, are you only selecting from this table or are you perhaps joining it to another table? If you have more than one child record in the joined table you will get multiple results.
Your code looks correct to me, unless there is something in the rest of the page I'm not seeing.
In the absence of any real clear conclusion on this my observation is that I think Red Element is on the right track when he states 'I think it has something to do with my web host as now every script that adds SQL data is doing the same thing'.
I had the problem outlined above and could not see what on earth caused this until I ran the same code on a different platform and it worked fine. I was originally testing in a localhost WAMP configuration but when I promoted the code to a real server, it worked no problem.
Therefore I suggest that if anyone else has the problem it is worth a try on a different server config.
I'd guess you have a problem with an .htaccess file which is making 2 requests to the same script. Log a message with a timestamp when you do your insert.

Categories