How to bind a few variables to a prepared statement as parameters using MySQLi in PHP

1 Answer

0 votes
$db_host        = 'localhost';
$db_user        = 'root';
$db_password    = '';
$db_name        = 'allonpage';

$con = new mysqli('localhost', $db_user, $db_password, $db_name);

if ($con->connect_error) 
    die('Connection Error: ' . $con->server_info);

$sql = "
  SELECT src, alt
  FROM images
  WHERE alt LIKE ?
  AND add_date BETWEEN ? AND ?
";    
 
// i = variable type integer
// d = variable type double
// s = variable type string
// b = variable type blob 
    
if ($stmt = $con->prepare($sql)) 
{
    $alt = 'w%';
    $date1 = '2016-07-01';
    $date2 = '2016-07-31';
    $stmt->bind_param('sss', $alt, $date1, $date2); // 'sss' = 3 variables type string

    $stmt->execute();
    if ($stmt->errno) 
       die("Error: " . $stmt->error);
 
    $stmt->bind_result($src, $alt);   
       
    while ($stmt->fetch()) 
    {
        echo $src . " - " . $alt . "<br />";
    }

    $stmt->close();
}

                                 
$con->close();


/*
run: 

http://www.ws.com/images/logo-wordpress.png - wordpress logo   
http://www.wp.com/images/why-choose.png - why choose us

*/

 



answered Jul 10, 2016 by avibootz
edited Jul 12, 2016 by avibootz
...