pyodbc example
import pyodbc
conn = pyodbc.connect('DSN=test;PWD=password')
c = conn.cursor()
c.execute('CREATE TABLE stocks (symbol varchar(10), price real)')
c.execute("INSERT INTO stocks VALUES (?, ?)", ('RHAT', 35.14))
c.execute('SELECT * FROM stocks WHERE symbol=?', ('RHAT', ))
print c.fetchone()
expected final queries (to be logged)
CREATE TABLE stocks(symbol varchar(10), price real)
INSERT INTO stocks VALUES('RHAT', 35.14)
SELECT * FROM stocks WHERE symbol = 'RHAT'
sqlite3 example
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('CREATE TABLE stocks (symbol text, price real)')
c.execute("INSERT INTO stocks VALUES (?, ?)", ('RHAT', 35.14))
c.execute('SELECT * FROM stocks WHERE symbol=?', ('RHAT', ))
print c.fetchone()
Sometimes it is more convenient to use a PreparedStatement object for sending SQL statements to the database. This special type of statement is derived from the more general class, Statement, that you already know.,If you want to execute a Statement object many times, it usually reduces execution time to use a PreparedStatement object instead.,No arguments are supplied to executeUpdate when they are used to execute updateSales and updateTotals; both PreparedStatement objects already contain the SQL statement to be executed.,Although you can use PreparedStatement objects for SQL statements with no parameters, you probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it. Examples of this are in the following sections.
public void updateCoffeeSales(HashMap<String, Integer> salesForWeek) throws SQLException {
String updateString =
"update COFFEES set SALES = ? where COF_NAME = ?";
String updateStatement =
"update COFFEES set TOTAL = TOTAL + ? where COF_NAME = ?";
try (PreparedStatement updateSales = con.prepareStatement(updateString);
PreparedStatement updateTotal = con.prepareStatement(updateStatement))
{
con.setAutoCommit(false);
for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey());
updateSales.executeUpdate();
updateTotal.setInt(1, e.getValue().intValue());
updateTotal.setString(2, e.getKey());
updateTotal.executeUpdate();
con.commit();
}
} catch (SQLException e) {
JDBCTutorialUtilities.printSQLException(e);
if (con != null) {
try {
System.err.print("Transaction is being rolled back");
con.rollback();
} catch (SQLException excep) {
JDBCTutorialUtilities.printSQLException(excep);
}
}
}
}
String updateString =
"update COFFEES " + "set SALES = ? where COF_NAME = ?";
// ...
PreparedStatement updateSales = con.prepareStatement(updateString);
updateSales.setInt(1, e.getValue().intValue()); updateSales.setString(2, e.getKey());
// changes SALES column of French Roast
//row to 100
updateSales.setInt(1, 100);
updateSales.setString(2, "French_Roast");
updateSales.executeUpdate();
// changes SALES column of Espresso row to 100
// (the first parameter stayed 100, and the second
// parameter was reset to "Espresso")
updateSales.setString(2, "Espresso");
updateSales.executeUpdate();
for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey());
// ...
}
updateSales.setInt(1, e.getValue().intValue()); updateSales.setString(2, e.getKey()); updateSales.executeUpdate(); updateTotal.setInt(1, e.getValue().intValue()); updateTotal.setString(2, e.getKey()); updateTotal.executeUpdate(); con.commit();
The following example creates a prepared statement that selects a specific album from the database. DB.Prepare returns an sql.Stmt representing a prepared statement for a given SQL text. You can pass the parameters for the SQL statement to Stmt.Exec, Stmt.QueryRow, or Stmt.Query to run the statement.,When you expect to execute the same SQL repeatedly, you can use an sql.Stmt to prepare the SQL statement in advance, then execute it as needed.,However, because an sql.Stmt already represents a preset SQL statement, its Exec, QueryRow, and Query methods take only the SQL parameter values corresponding to placeholders, omitting the SQL text.,Conn.PrepareContext creates a prepared statement from an sql.Conn, which represents a reserved connection.
The following example creates a prepared statement that selects a specific
album from the database. DB.Prepare
returns an sql.Stmt
representing a
prepared statement for a given SQL text. You can pass the parameters for the
SQL statement to Stmt.Exec
, Stmt.QueryRow
, or Stmt.Query
to run the
statement.
// AlbumByID retrieves the specified album.
func AlbumByID(id int)(Album, error) {
// Define a prepared statement. You'd typically define the statement
// elsewhere and save it for use in functions such as this one.
stmt,
err: = db.Prepare("SELECT * FROM album WHERE id = ?")
if err != nil {
log.Fatal(err)
}
var album Album
// Execute the prepared statement, passing in an id value for the
// parameter whose placeholder is ?
err: = stmt.QueryRow(id).Scan( & album.ID, & album.Title, & album.Artist, & album.Price, & album.Quantity)
if err != nil {
if err == sql.ErrNoRows {
// Handle the case of no rows returned.
}
return album, err
}
return album,
nil
}
Then the query finally gets executed. Means variables get sent to the database server and the query is actually executed. ,Then, the query is prepared. The idea is very smart. To avoid even a possibility of the SQL injection or a syntax error caused by the input data, the query and the data are sent to database server separately. So it goes on here: with prepare() we are sending the query to the database server ahead. A special variable, a statement is created as a result. We would use this variable from now on. ,Replace all variables in the query with question marks (called placeholders or parameters),However, in a modern web-application the database interaction is separated from the HTML output. It makes the code much cleaner and more flexible. It means that we should never print our data using a while loop but rather collect it into array and then use this array for the output.
Long story short, here is the code:
$sql = "SELECT * FROM users WHERE id=?"; // SQL with parameters$stmt = $conn->prepare($sql); $stmt->bind_param("i", $id);$stmt->execute();$result = $stmt->get_result(); // get the mysqli result$user = $result->fetch_assoc(); // fetch data
Let's see what does every line of this code mean
$sql = "SELECT * FROM users WHERE id=?";
IMPORTANT! there should be no quotes around question marks, you are adding placeholders, not strings.
$stmt = $conn - > prepare($sql);
So now you can tell that "s" means "there would be 1 variable, of string type".
$stmt - > execute();
NOTE that you don't have to check the execution result. Given you have the proper connection code mentioned above, in case of error mysqli will raise an error automatically.
$result = $stmt - > get_result(); // get the mysqli result
Firstly thanks for the site! As a PHP newbie its great to have code samples. I'm trying to do something which should be simple.
$sql = "SELECT * FROM users WHERE id=6";
works as I expect it to but
$id = 6;
$sql = "SELECT * FROM users WHERE id=?";
$stmt = $conn - > prepare($sql);
$stmt - > bind_param("i", $id);
$stmt - > execute();
Hello. I have a function to display a data. Your help is much appreciated. Thanks.
function get_title1() { global $db; $stmt = $db->prepare( "SELECT * FROM music WHERE id =?"); $stmt->bind_param('i', $id); $stmt->execute(); $result = $stmt->get_result(); while($data = $result->fetch_array(MYSQLI_ASSOC)) { echo nl2br($data['title1']), "<b><br><h2><p><a>"; $stmt->close(); }}
Got your reply, thanks! But I keep getting a 500 internal server error on this exact code (when I remove it, the script works):
if (isset($code)) {
$stmt = $db2 - > prepare('SELECT * FROM accounts WHERE activation_code = ?)'; $stmt - > bind_param('s', $_GET['code']); $stmt - > execute(); $result = $stmt - > get_result(); $name2 = $row['user_refer']; $mail = $row['user_email'];
}
Cool tut! Thanks! Quick question: I'm trying to retrieve data from a mysql DB based on the existence of a code. I used this:
$stmt = $db2 - > prepare('SELECT * FROM accounts WHERE activation_code = ?)'; $stmt - > bind_param('s', $_GET['code']); $stmt - > execute(); $result = $stmt - > get_result();
while ($row = $result - > fetch_assoc()) {
$row['user_refer'] = $name2;
$row['user_email'] = $mail;
}
$stmt - > close();
Yes you made it almost right, but for the assignment part, it works the opposite:
$name2 = $row['user_refer'];
$mail = $row['user_email'];
Hence the correct code would be
$stmt = $db2 - > prepare('SELECT * FROM accounts WHERE activation_code = ?)'; $stmt - > bind_param('s', $_GET['code']); $stmt - > execute(); $result = $stmt - > get_result(); $name2 = $row['user_refer']; $mail = $row['user_email'];
You can use it from any program that can send SQL statements to the server to be executed, such as the mysql client program. , To use prepared statements when you do not have access to a programming API that supports them. , SQL syntax for prepared statements is intended to be used for situations such as these: , To create a test case that reproduces a problem with prepared statements, so that you can file a bug report.
The first example shows how to create a prepared statement by using a string literal to supply the text of the statement:
mysql > PREPARE stmt1 FROM 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse';
mysql > SET @a = 3;
mysql > SET @b = 4;
mysql > EXECUTE stmt1 USING @a, @b; +
-- -- -- -- -- -- +
|
hypotenuse |
+ -- -- -- -- -- -- +
|
5 |
+ -- -- -- -- -- -- +
mysql > DEALLOCATE PREPARE stmt1;
The second example is similar, but supplies the text of the statement as a user variable:
mysql > SET @s = 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse';
mysql > PREPARE stmt2 FROM @s;
mysql > SET @a = 6;
mysql > SET @b = 8;
mysql > EXECUTE stmt2 USING @a, @b; +
-- -- -- -- -- -- +
|
hypotenuse |
+ -- -- -- -- -- -- +
|
10 |
+ -- -- -- -- -- -- +
mysql > DEALLOCATE PREPARE stmt2;
Here is an additional example that demonstrates how to choose the table on which to perform a query at runtime, by storing the name of the table as a user variable:
mysql > USE test;
mysql > CREATE TABLE t1(a INT NOT NULL);
mysql > INSERT INTO t1 VALUES(4), (8), (11), (32), (80);
mysql > SET @table = 't1';
mysql > SET @s = CONCAT('SELECT * FROM ', @table);
mysql > PREPARE stmt3 FROM @s;
mysql > EXECUTE stmt3; +
-- -- +
|
a |
+ -- -- +
|
4 |
|
8 |
|
11 |
|
32 |
|
80 |
+ -- -- +
mysql > DEALLOCATE PREPARE stmt3;
Prepares the SQL query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement. , The query, as a string. It must consist of a single SQL statement. , The SQL statement may contain zero or more parameter markers represented by question mark (?) characters at the appropriate positions. , The statement template can contain zero or more question mark (?) parameter markers—also called placeholders. The parameter markers must be bound to application variables using mysqli_stmt_bind_param() before executing the statement.
Amersfoort is in district Utrecht
The prepared statement execution consists of two stages: prepare and execute.,In this tutorial you will learn how to use prepared statements in MySQL using PHP.,The following example will show you how prepared statements actually work:
< ? php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if ($link === false) {
die("ERROR: Could not connect. ".mysqli_connect_error());
}
// Prepare an insert statement
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES (?, ?, ?)";
if ($stmt = mysqli_prepare($link, $sql)) {
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $first_name, $last_name, $email);
/* Set the parameters values and execute
the statement again to insert another row */
$first_name = "Hermione";
$last_name = "Granger";
$email = "hermionegranger@mail.com";
mysqli_stmt_execute($stmt);
/* Set the parameters values and execute
the statement to insert a row */
$first_name = "Ron";
$last_name = "Weasley";
$email = "ronweasley@mail.com";
mysqli_stmt_execute($stmt);
echo "Records inserted successfully.";
} else {
echo "ERROR: Could not prepare query: $sql. ".mysqli_error($link);
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link); ?
>
< ? php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$mysqli = new mysqli("localhost", "root", "", "demo");
// Check connection
if ($mysqli === false) {
die("ERROR: Could not connect. ".$mysqli - > connect_error);
}
// Prepare an insert statement
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES (?, ?, ?)";
if ($stmt = $mysqli - > prepare($sql)) {
// Bind variables to the prepared statement as parameters
$stmt - > bind_param("sss", $first_name, $last_name, $email);
/* Set the parameters values and execute
the statement again to insert another row */
$first_name = "Hermione";
$last_name = "Granger";
$email = "hermionegranger@mail.com";
$stmt - > execute();
/* Set the parameters values and execute
the statement to insert a row */
$first_name = "Ron";
$last_name = "Weasley";
$email = "ronweasley@mail.com";
$stmt - > execute();
echo "Records inserted successfully.";
} else {
echo "ERROR: Could not prepare query: $sql. ".$mysqli - > error;
}
// Close statement
$stmt - > close();
// Close connection
$mysqli - > close(); ?
>
< ? php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if ($link === false) {
die("ERROR: Could not connect. ".mysqli_connect_error());
}
// Prepare an insert statement
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES (?, ?, ?)";
if ($stmt = mysqli_prepare($link, $sql)) {
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $first_name, $last_name, $email);
// Set parameters
$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$email = $_REQUEST['email'];
// Attempt to execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
echo "Records inserted successfully.";
} else {
echo "ERROR: Could not execute query: $sql. ".mysqli_error($link);
}
} else {
echo "ERROR: Could not prepare query: $sql. ".mysqli_error($link);
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link); ?
>
< ? php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$mysqli = new mysqli("localhost", "root", "", "demo");
// Check connection
if ($mysqli === false) {
die("ERROR: Could not connect. ".$mysqli - > connect_error);
}
// Prepare an insert statement
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES (?, ?, ?)";
if ($stmt = $mysqli - > prepare($sql)) {
// Bind variables to the prepared statement as parameters
$stmt - > bind_param("sss", $first_name, $last_name, $email);
// Set parameters
$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$email = $_REQUEST['email'];
// Attempt to execute the prepared statement
if ($stmt - > execute()) {
echo "Records inserted successfully.";
} else {
echo "ERROR: Could not execute query: $sql. ".$mysqli - > error;
}
} else {
echo "ERROR: Could not prepare query: $sql. ".$mysqli - > error;
}
// Close statement
$stmt - > close();
// Close connection
$mysqli - > close(); ?
>