1

Is there a way you can set field names in php prepared statements, instead of just setting there values, for example,

$stmt = $mysqli->prepare("UPDATE movies SET filmName = ?, 
   filmDescription = ?, 
  filmImage = ?,  
  filmPrice = ?,  
  filmReview = ?  
   WHERE filmID = ?");
$stmt->bind_param('sssdii',
  $_POST['filmName'],
  $_POST['filmDescription'],
  $_POST['filmImage'],
  $_POST['filmPrice'], 
  $_POST['filmReview'],
  $_POST['filmID']);
 $stmt->execute(); 
$stmt->close();

is there a simpler way to do that? For example, is there a way I can do something like

 $stmt->bind_param($_POST);

so it binds everything in with the correct names?

Enchanta Support
  • 199
  • 1
  • 2
  • 11

1 Answers1

0

I hope this helps. I did not test, but if I missed something, please comment and I will edit.

$sql = "UPDATE 
            movies 
        SET 
            filmName = ?, 
            filmDescription = ?, 
            filmImage = ?,  
            filmPrice = ?,  
            filmReview = ?  
        WHERE 
            filmID = ?";

$arrayFields = array("filmName" => "s"
                    , "filmDescription" => "s"
                    , "filmImage" => "s"
                    , "filmPrice" => "d"
                    , "filmReview" => "i"
                    , "filmID" => "i");

$stmt = $mysqli->prepare($sql);

foreach($_POST as $key=>$val) {

    if(array_key_exists ( $key , $arrayFields )) {

        $stmt->bind_param($arrayFields[$key], $_POST[$key]);
    }
}
$stmt->execute();   

$stmt->close();
meda
  • 45,103
  • 14
  • 92
  • 122
gbvisconti
  • 412
  • 1
  • 4
  • 19
  • wouldnt be nice if this was possible, unfortunately this wont work with mysqli – meda Dec 03 '14 at 22:51
  • What if instead of '?' he uses :filmName, for example? Is it possible in mysqli? Then it's just use the $key inside the loop to bind it – gbvisconti Dec 03 '14 at 22:56
  • only PDO allows that, I modified your code to show how to do it in PDO – meda Dec 03 '14 at 22:58
  • hummm, I will try to edit my answer considering that restriction in mysqli – gbvisconti Dec 03 '14 at 23:01
  • 1
    What about this: http://stackoverflow.com/questions/12486032/binding-an-unknown-number-of-parameters-using-mysqli – gbvisconti Dec 03 '14 at 23:08
  • 1
    the problem is mysqli is like fake OOP, its not flexible, there are way to write custom functions but it is messy. thats why people ditch it in favor of PDO – meda Dec 03 '14 at 23:21