PDO parameters not working at all

Asked
Active3 hr before
Viewed126 times

7 Answers

working
90%

Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers , This give me another error -_- Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables in /var/www/html/crawlnew.php on line 435 – Cornezuelo del Centeno Apr 21 '15 at 11:45 , your solution gives me Fatal error: Call to undefined method PDOStatement::bind_param() in /var/www/html/crawlnew.php on line 432 – Cornezuelo del Centeno Apr 21 '15 at 11:43 , I supose, but I don't understand why. Replacing the parameter with a string, and ID with a number, the query works right. Variables $jsonvprencode and $idvpr are valid strings as well :S – Cornezuelo del Centeno Apr 21 '15 at 11:50

MySQLi with PreparedStatements

$stmt = $conn - > prepare("UPDATE `wp_posts` SET  `post_content` = ? WHERE `ID` = ?");
$stmt - > bind_param("si", $jsonvprencode, $idvpr);

PDO with Prepared Statements

$stmt = $conn - > prepare("UPDATE `wp_posts` SET  `post_content` = :jsonvprencode WHERE `ID` = :idvpr");

$stmt - > bindParam(':jsonvprencode', $jsonvprencode);

$stmt - > bindParam(':idvpr', $idvpr);
load more v
88%

Example #1 Execute a prepared statement with named placeholders,PDOStatement::bindParam — Binds a parameter to the specified variable name ,Example #2 Execute a prepared statement with question mark placeholders,PDOStatement::bindValue() - Binds a value to a parameter

load more v
72%

use bindValue() instead of bindParam(). bindParam() binds to a reference, so when you execute the query all the parameters use the last value of $val.,EDIT : I solved my problem using bindValue() instead.,The only difference is what ends up in the general query log when the parameter is bound before prepare versus after prepare.,But when I used bindParam() in foreach() then I got an empty array() as result. Below the codes

I am using PDO for an application but getting a problem for PDO bindParam(). I have an array and I want to use the values of array for PDO bindParam() using for loop or foreach() but an unexpected result is getting by foreach(). When I used bindParam() in for loop, it worked fine. What I tried was

$con = $this - > connection();
$stmt = $con - > prepare($sql);

for ($i = 0; $i < count($params); $i++) {
   $stmt - > bindParam($i + 1, $params[$i], PDO::PARAM_STR, 10);
}
$stmt - > execute();
$result = $stmt - > fetchAll(); //$result is OK

But when I used bindParam() in foreach() then I got an empty array() as result. Below the codes

$con = $this - > connection();
$stmt = $con - > prepare($sql);

foreach($params as $key => $val) { //Here
   $stmt - > bindParam($key + 1, $val, PDO::PARAM_STR, 10);
}
$stmt - > execute();
$result = $stmt - > fetchAll(); //$result is an empty array
load more v
65%

How to create a WHERE clause for PDO dynamically,Create the query dynamically,It's already there: https://phpdelusions.net/mysqli_examples/search_filter,The dynamic where clause stuff looks interesting. What is the performance impact of this solution?

PDO doesn't have a functionality for this out of the box, but it can ease the task significantly, thanks again to its ability to bind the arbitrary number of parameters in the form of array passed to execute(). So we can use a conditional statement which will add a condition to the query and also a parameter to bind:

// always initialize a variable before use!$conditions = [];$parameters = [];// conditional statementsif (!empty($_GET['name'])){    // here we are using LIKE with wildcard search    // use it ONLY if really need it    $conditions[] = 'name LIKE ?';    $parameters[] = '%'.$_GET['name']."%";}if (!empty($_GET['sex'])){    // here we are using equality    $conditions[] = 'sex = ?';    $parameters[] = $_GET['sex'];}if (!empty($_GET['car'])){    // here we are using not equality    $conditions[] = 'car != ?';    $parameters[] = $_GET['car'];}if (!empty($_GET['date_start']) && $_GET['date_end']){    // BETWEEN    $conditions[] = 'date BETWEEN ? AND ?';    $parameters[] = $_GET['date_start'];    $parameters[] = $_GET['date_end'];}// the main query$sql = "SELECT * FROM users";// a smart code to add all conditions, if anyif ($conditions){    $sql .= " WHERE ".implode(" AND ", $conditions);}// the usual prepare/execute/fetch routine$stmt = $pdo->prepare($sql);$stmt->execute($parameters);$data = $stmt->fetchAll();

We can actually use a conditional statement right in the query. A condition like (name = :name or :name is null) will return true if either the value matches the field's contents or if the value is null. It means that if we want the query to bypass a condition, we just have to pass null for the value. ong story short, here it goes:

$parameters['name'] = !empty($_GET['name']) ? "%".$_GET['name'].
"%": null;
$parameters['sex'] = !empty($_GET['sex']) ? $_GET['sex'] : null;
$parameters['car'] = !empty($_GET['car']) ? $_GET['car'] : null;
$sql = "SELECT * FROM users WHERE (name LIKE :name or :name is null)AND   (sex  = :sex  or :sex  is null)AND   (car  != :car  or :car  is null)";
$stmt = $pdo - > prepare($sql);
$stmt - > execute($parameters);
$data = $stmt - > fetchAll();

The only drawback here is that this code will work only if emulation is turned off. So, to make it universal, we have to make it a little bit more verbose

$param['name'] = $param['name1'] = !empty($_GET['name']) ? "%".$_GET['name'].
"%": null;
$param['sex'] = $param['sex1'] = !empty($_GET['sex']) ? $_GET['sex'] : null;
$param['car'] = $param['car1'] = !empty($_GET['car']) ? $_GET['car'] : null;
$sql = "SELECT * FROM users WHERE (name LIKE :name or :name1 is null)AND   (sex  = :sex  or :sex1  is null)AND   (car  != :car  or :car1  is null)";
$stmt = $pdo - > prepare($sql);
$stmt - > execute($param);
$data = $stmt - > fetchAll();
load more v
75%

Prepare and execute a statement that includes variable input.,To prepare and execute an SQL statement that includes parameter markers:,To prepare and execute an SQL statement that includes variable input, use the PDO::prepare, PDOStatement::bindParam, and PDOStatement::execute methods. Preparing a statement improves performance because the database server creates an optimized access plan for data retrieval that it can reuse if the statement is executed again. ,If the function call succeeds, it returns a PDOStatement object that you can use in subsequent method calls that are related to this query.

Prepare and execute a statement that includes variable input.

$sql = "SELECT firstnme, lastname FROM employee WHERE bonus > ? AND bonus < ?";
$stmt = $conn - > prepare($sql);
if (!$stmt) {
   // Handle errors
}

// Explicitly bind parameters
$stmt - > bindParam(1, $_POST['lower']);
$stmt - > bindParam(2, $_POST['upper']);

$stmt - > execute($stmt);

// Invoke statement again using dynamically bound parameters
$stmt - > execute($stmt, array($_POST['lower'], $_POST['upper']));
40%

This example shows how to use PDO::prepare with parameter markers and a forward-only cursor.,This example shows how to use PDO::prepare with PDO::ATTR_EMULATE_PREPARES set to true.,This example shows how to use PDO::prepare with a server-side static cursor. For an example showing a client-side cursor, see Cursor Types (PDO_SQLSRV Driver).,If user wishes to bind parameters with different encodings (for instance, UTF-8 or binary), user should clearly specify the encoding in the PHP script.

Syntax

PDOStatement PDO::prepare($statement[, array(key_pair)])
load more v
22%

The same concept as the example right before, but this is handy if all you need to do is get the an array of only one column.,However, this will not work. This is how you would do it the right way.,Another unexpected, yet potentially useful behavior this has is that you can modify private variables. I'm really not sure how I feel about this, as this seems to violate principles of encapsulation.,As you can see, PDO clearly excels in this too, as the code is much shorter, due to not needing to specify the type with bindValue() or bindParam().

I recommend creating a file named pdo_connect.php and place it outside of your root directory (ex: html, public_html).

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
   PDO::ATTR_EMULATE_PREPARES => false, // turn off emulation mode for "real" prepared statements
   PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
   PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
   $pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
   error_log($e - > getMessage());
   exit('Something weird happened'); //something a user can understand
}
load more v

Other "working-undefined" queries related to "PDO parameters not working at all"