1

Right now I'm currently attempting to make a MySQLi class to make typing code easier and so it looks cleaner and is more usable overall.

I'm attempting to write a function which will execute a query with a prepared statement. My dilemma is this:

  public function safeRead($query, $data, $params)
  {
    $stmt = $mysqli->prepare($query);
    $stmt->bind_param($params, $data);
    $stmt->execute();
    $result = $stmt->get_result();
    $check = $result->fetch_assoc();      
  }

I of course want to execute a query, as you can see. My problem lies with the $data variable. How can I/is it possible to pass data, as a string and possibly convert to an array or something usable so it can be used with bind_param ?

8
  • 1
    explode converts a string into array. Commented Oct 7, 2013 at 13:20
  • Although I quite familiar with binding problem in general, I have not a slightest idea, why do you need a string. Commented Oct 7, 2013 at 13:21
  • 1
    It's not clear what you're asking. if it's about dealing with IN operator, then just check if passed parameter is an array with is_array() and then join() it into string Commented Oct 7, 2013 at 13:22
  • Could you please show your query and string example? Commented Oct 7, 2013 at 13:22
  • 1
    Finally I got ot. You don't need no string at all. Here you can see the code Commented Oct 7, 2013 at 13:26

1 Answer 1

-1

bind_param prototype looks like this:

bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )

so it accepts a string of types sssd, and a bunch of variables for those types

Assuming you are passing in the correct type of variables

$stmt->bind_param($params, $data);

A way to do this would be

   public function safeRead($query, $data, $params)
   {
    $stmt = $mysqli->prepare($query);
    $params = str_split( $params ); // Split the params 'sssd'
    foreach( $data as $k => $v ) {
        $stmnt->bind_param( $params[$k], $data[$k] );
    }
    $stmt->execute();
    $result = $stmt->get_result();
    $check = $result->fetch_assoc();      
  }

This is untested.


Edit

Since the second parameter of bind_param is passed by reference you MAY need to create an intermediate variable before binding, instead of binding the array item.

foreach( $data as $k => $v ) {
    $var_name = 'var'.$k;
    $$var_name = $v;
    $stmnt->bind_param( $params[$k], $$var_name );
}

but im not 100% sure.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.