Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is $stmt in PHP

Tags:

php

mysqli

What exactly is $stmt and what is it's purpose? what does it stand for..

I'm following a tutorial that is using prepared statements and looked up stmt in the manual: http://php.net/manual/en/class.mysqli-stmt.php

and see that it is a class that "represents a prepared statement" - which i guess is a prepared sql statement that you slot a variable into. though I don't see how this id different to storing a sql statement as a string and then manipulating the string to add variables when you need?

like image 489
Zach Smith Avatar asked Nov 23 '14 08:11

Zach Smith


3 Answers

"$stmt" obviously (I think) stands for "statement". As a variable name it's arbitrary, you can name that variable anything you want. $stmt is just rather idiomatic.

A prepared statement as such is a database feature. The database itself takes the query in two steps: first the query structure with placeholders, second the data to fill in the placeholders. The statement objects on the PHP side represent this separation and are there to give you a handle representing the prepared statement on the SQL server side.

The point of this separation is that there's no chance of having SQL injection problems due to incorrectly escaped arbitrary string values; it is also useful for performance if you reuse that prepared statement a number of times.

like image 131
deceze Avatar answered Sep 19 '22 13:09

deceze


Working with statements is much safer than inserting variables into a plain SQL string. By using statements you prevent SQL injection. Take a look at:

How does the SQL injection from the "Bobby Tables" XKCD comic work?

&

How can I prevent SQL injection in PHP?

like image 27
Tom Avatar answered Sep 18 '22 13:09

Tom


What exactly is $stmt and what is it's purpose?

It is a variable and stores a value

People do use it for statement - others are a bit more imaginative with variables name

like image 23
Ed Heal Avatar answered Sep 22 '22 13:09

Ed Heal