Home > database, mysql, PHP, SQL > Server-side prepared statements in Mysql

Server-side prepared statements in Mysql

Hey buddies,
I learned prepared statements in Mysql.
I would like to share my learning.
Why use prepared statements?
1. Prepared statements can help increase security by separating SQL logic from the data being supplied. This separation of logic and data can help prevent a very common type of vulnerability called an SQL injection attack. Normally when you are dealing with an ad hoc query, you need to be very careful when handling the data that you received from the user.
This is unnecessary when dealing with prepared statements. The separation of the data allows MySQL to automatically take into account these characters and they do not need to be escaped using any special function.
2. Increase in performance: First is the need to only parse the query a single time. When you initially prepare the statement, MySQL will parse the statement to check the syntax and set up the query to be run. Then if you execute the query many times, it will no longer have that overhead. This pre-parsing can lead to a speed increase if you need to run the same query many times.
The second place where performance may increase is through the use of the new binary protocol that prepared statements can use. The traditional protocol in MySQL always converts everything into strings before sending them across the network. This means that the client converts the data into strings, which are often larger than the original data, sends it over the network (or other transport) to the server, which finally decodes the string into the correct datatype. The binary protocol removes this conversion overhead. All types are sent in a native binary form, which saves the conversion CPU usage, and can also cut down on network usage.
Dis-advantage:
Prepared statements can actually be slower than regular queries. The reason for this is that there are two round-trips to the server, which can slow down simple queries that are only executed a single time.

Categories: database, mysql, PHP, SQL
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.