问题描述:

I am somewhat new to php and mysql. I have looked at many post about prepared statements and can't seem to find my exact scenario.

Should I use a prepared statement in this scenario?

I am creating a FPDF report of records using a query based on a date range.

While I am displaying each row of data I have another query within the "while" statement that pulls the username data associated with that specific record because the "usernameID" field pulls data via a foreign key in another table. Since this internal query is called more than once before the page finishes loading, should it be a prepared statement?

I know that I can INNER JOIN these tables and have in some scenarios but I am just asking in trying to understand prepared statements better. Is that what it is for, or should they be used for frequently used queries within a session.

I guess what I am getting at is, would the webpage have better performance with the INNER JOIN or should the queries be separated and have prepared statements for the username data that is based on an ID over and over as the page loads?

I have users who keep a session open that when a page is submitted will resend the page for new data, but before that point the connection is closed until they click submit again, so I don't need prepared statements, right?

I welcome any links or better explanations of when or examples to using prepared statements. Sorry if this has been answered already but I appreciate any insight.

Thanks,

T-Boy

网友答案:

exactly its better to use prepared statement but if in case your database is having little data to be handled then a inner join will help you and that will not give much difference in the performance aspect. but if your database is dealing with a tables with huge data inside then its always advisable to use prepared statement.

In prepared statement, the query only will be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. For complex queries this process can take up enough time that it will noticeably slow down an application if there is a need to repeat the same query many times with different parameters. By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster.

As per your requirement to generate the reports that will be handled with multiple tables and queries its advisable to use prepared statement but still depends on the data in the table.

相关阅读:
Top