If you want to manage a prepared statement using PDO, try the following code:
<?php
$servername = "hostname";
$username = "username";
$password = "password";
$dbname = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare SQL content
$sql = "SELECT * FROM Persons";
// Considering this is the array you want to use to prepare the SQL content
$params = array("LastName" => 1, "FirstName" => 1, "Address" => 1);
foreach($params as $attr => $val) {
$where[] = "$attr = :$attr";
}
$sql .= " where " . join(' and ', $where); // *** where LastName = :LastName and FirstName = :FirstName and Address = :Address
$stmt = $conn->prepare($sql); // *** SELECT * FROM Persons where LastName = :LastName and FirstName = :FirstName and Address = :Address
// Bind parameters
foreach($params as $attr => $val) {
$stmt->bindValue(":$attr", $val, PDO::PARAM_STR);
}
$stmt->execute();
//$stmt->debugDumpParams();
echo $stmt->rowCount();
print_r($stmt->fetch());
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
Or if you want to manage a prepared statement using mysqli, try the following:
<?php
$servername = "hostname";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Persons";
// Considering this is the array you want to use to prepare the SQL content
$params = array("LastName" => 1, "FirstName" => 0, "Address" => 1);
$sqltype = "";
foreach($params as $attr => $val) {
$where[] = "$attr = ?";
$sqltype .= 's';
$bind_val[] = $val;
}
$sql .= " where " . join(' and ', $where); // *** SELECT * FROM Persons where LastName = ? and FirstName = ? and Address = ?
// Prepare SQL content
$stmt = $conn->prepare($sql);
// Bind parameters
$stmt->bind_param( $sqltype, ...$bind_val ); // *** $stmt->bind_param("sss", 1, 0, 1);
$stmt->execute();
$result = $stmt->get_result();
echo $result->num_rows;
print_r($result);