However, we want to choose the name at run time and store it in a variable called person_name. You could accept the value in as an argument passed into a function, but we’ll just set a variable to keep it simple.

This is very dangerous and opens our code to a SQL Injection attack. You can follow that link for more information, but we won’t be going into detail in this series. Just know that you should, generally, never allow end user input to be fed directly into a dynamic SQL statement.

A much safer way to pass external values into the SQL statement is by using bind variables with prepared statements.

You have a couple different options:

Placeholders:

1

2

3

4

5

6

7

my$sth=$con-&gt;prepare("select id, name, age, notes from lcs_people where name = ? and age = ?");

$sth-&gt;bind_param(1,'Bob');

$sth-&gt;bind_param(2,35);

my$sth=$con-&gt;prepare("select id, name, age, notes from lcs_people where name = ? and age = ?");

$sth-&gt;bind_param(2,35);

$sth-&gt;bind_param(1,'Bob');

Notice the bind_param(1, and bind_param(2, are switched in the two examples. With a placeholders statement, you use a ? to indicate where the bind variable value goes, then when you assign the bind_param you indicate which placeholder to assign the value to.

Named:

1

2

3

4

5

6

7

my$sth=$con-&gt;prepare("select id, name, age, notes from lcs_people where name = :name and age = :age");

$sth-&gt;bind_param(":name",'Bob');

$sth-&gt;bind_param(":age",35);

my$sth=$con-&gt;prepare("select id, name, age, notes from lcs_people where name = :name and age = :age");

$sth-&gt;bind_param(":age",35);

$sth-&gt;bind_param(":name",'Bob');

With this method, the :name variable will be assigned the value of ‘name’ in the provided key value set.

Notice, in both examples, that we do not wrap the bind variable for the name with quotes. This is handled automatically when the statement is prepared for execution.

In this section, we took a look at some basic query functionality. When you experiment with more complex queries, if you run into problems leave a comment here or on twitter and we’ll find an answer together.

Some things you could try

Join the lcs_people and lcs_pets table to get the people and their pets

Only retrieve the person’s name and age

Change the order to display in descending order.

Hint – If you have trouble getting a query to run in your code, try running it in SQL Plus or another database console tool. This will help determine if the problem is with the query or the code.