SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2011
    0 Post(s)
    0 Thread(s)

    How to bind parameters dynamically

    I want to bind mysqli parameters dynamically using php. The problem I have is adapting my code to do this. I have seen a question which should be helpful to be able to solve this problem which is but I dont know how to use that code to adapt it into my code. I am really struggling to understand it. It will be easier for me to see somebody adapt my code to fit the bill so then I can understand what is going on.

    Can somebody help guide me what I need to do to be able to bind the parameters dynamically in my code? Do I just need to change the bind param method to a call_func_user_array or is it much more than that?

    Below is my code:
        $questionquery = "SELECT q.QuestionContent FROM Question q WHERE ";
        $whereArray = array();
        $orderByArray = array();
        $orderBySQL = "";
        $paramString = "";
        //loop through each term
        foreach ($terms as &$each) {
            //if only 1 term entered then perform this LIKE statement
            if ($i == 1){
                $questionquery .= "q.QuestionContent LIKE ? ";
            } else {
                //If more than 1 term then add an OR statement
                $questionquery .= "OR q.QuestionContent LIKE ? ";
                $orderBySQL .= ",";
            $orderBySQL .= "IF(q.QuestionContent LIKE ? ,1,0)"; 
            $whereArray[] = "%" . $each . "%";
            $orderByArray[] = "%" . $each . "%"; 
            $paramString .= "ss";
        $questionquery .= "GROUP BY q.QuestionId, q.SessionId ORDER BY " . $orderBySQL; 
        $stmt=$mysqli->prepare($questionquery)or die($mysqli->error); ;  
        $stmt->bind_param($paramString, array_merge($whereArray, $orderByArray));
        	$questionnum = $stmt->num_rows();
    Thank you and I appreciate your help

  2. #2
    SitePoint Addict kduv's Avatar
    Join Date
    May 2012
    Maui, HI
    5 Post(s)
    0 Thread(s)
    If you print out $questionquery before you try to prepare it, you'll see that you have some errors in your SQL.
    SELECT q.QuestionContent FROM Question q WHERE q.QuestionContent LIKE ? OR q.QuestionContent LIKE ? OR q.QuestionContent LIKE ? GROUP BY q.QuestionId, q.SessionId ORDER BY IF(q.QuestionContent LIKE ? ,1,0),IF(q.QuestionContent LIKE ? ,1,0),IF(q.QuestionContent LIKE ? ,1,0)
    I'd fix those first, then see what happens.

    I assigned some search terms (4) to mess around with. If you can provide an example of what the $terms array may look like, and any errors you receive when you run the script, it may be easier to help.

Tags for this Thread


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts