shadd Posted July 10 Share Posted July 10 how can I make this work .I need to pass table name as variable and concat this query all together -- Prepare ansstatement PREPARE ansstatement FROM "CONCAT('INSERT INTO ',?,'(Ans_Id,Answer,answer_img) VALUES("',?,'","',? ,'","',?,'")' )"; -- Define query parameters SET @p1 = l_table_name; SET @p2 = inQueId; Quote Link to comment https://forums.phpfreaks.com/topic/322251-hoto-make-prepared-statement/ Share on other sites More sharing options...
Solution Barand Posted July 10 Solution Share Posted July 10 1 hour ago, shadd said: .I need to pass table name as variable Not allowed. Only values can be passed as parameters, not table or column identifiers. Having variable table names is oftenindicative of a poor database design. Don't insert primary keys (Ans_id) in INSERT statements, let them be created automatically. $stmt = $pdo->prepare("INSERT INTO tablename (answer, answer_image) VALUES (?, ?)"); $stmt->execute( [ $answer, $image_path ] ); Quote Link to comment https://forums.phpfreaks.com/topic/322251-hoto-make-prepared-statement/#findComment-1629613 Share on other sites More sharing options...
Strider64 Posted July 12 Share Posted July 12 If you are trying to enter data, but you don't know exactly how many fields (columns) you are going to be saving to the table then you could do something like the following. Though would still need the correct table's column names and the corresponding data that goes with it. Here's an example -> function create(array $data, $pdo, $table) { try { /* Initialize an array */ $attribute_pairs = []; /* * Set up the query using prepared states with the values of the array matching * the corresponding keys in the array * and the array keys being the prepared named placeholders. */ $sql = 'INSERT INTO ' . $table . ' (' . implode(", ", array_keys($data)) . ')'; $sql .= ' VALUES ( :' . implode(', :', array_keys($data)) . ')'; /* * Prepare the Database Table: */ $stmt = $pdo->prepare($sql); /* * Grab the corresponding values in order to * insert them into the table when the script * is executed. */ foreach ($data as $key => $value) { if($key === 'id') { continue; } // Don't include the id: $attribute_pairs[] = $value; // Assign it to an array: } return $stmt->execute($attribute_pairs); // Execute and send boolean true: } catch (PDOException $e) { if ($e->errorInfo[1] === 1062) { return false; } throw $e; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; // Not for a production server: } return true; } Quote Link to comment https://forums.phpfreaks.com/topic/322251-hoto-make-prepared-statement/#findComment-1629837 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.