0

i'm trying to insert values into a mysql table using inputs from another page using $_POST and a prepared statement. My understanding is that you need to use the bindParam function for each of the variables being inserted because you cant use variables in a mysql query.

My issue is that the bindParam function requires the length of the variable being binded and the variable's value is unknown because it is decided by the user input.

Do I have to create a variable for the string length of the variable I want to assign a Param to?

if(isset($_POST['name_input'])) {    
    $name = $_POST['name_input'];  
    $genre = $_POST['genre_input'];  
    $size = $_POST['size_input'];  
    $rating = $_POST['rating_input'];  
    $date = $_POST['date_input'];  
}

if(!empty($name)) {   
$addedQuery = $db->prepare(
     "INSERT INTO `torrent_list` (`movie_name`, 
`movie_genre`,`file_size`, `rating`,
`release_date`) VALUES (NULL, ':name', ':genre', ':size', ':rating', 
':date')");


$addedQuery->bindValue(':name', $name, PDO::PARAM_STR);   
$addedQuery->bindValue(':genre', $genre, PDO::PARAM_STR);  
$addedQuery->bindValue(':size', $size, PDO::PARAM_STR);  
$addedQuery->bindValue(':rating', $rating, PDO::PARAM_STR);  
$addedQuery->bindValue(':date', $date, PDO::PARAM_STR);  


$addedQuery->execute(
);
}

Thanks.

  • 3
    Can you add some code for context? The length argument is optional and is described as " To indicate that a parameter is an OUT parameter from a stored procedure, you must explicitly set the length." Are you using stored procedures? – tadman Jan 08 '18 at 22:58
  • 1
    what @tadman said. plus, we use `bindValue` instead of `bindParam` if we are passing values *into* the statement. We could use `bindParam`, but the big difference is that values provided by `bindValue` are evaluated at the time `bindValue` is executed. But `bindParam` binds a *reference* to a variable, and evaluation of the value is deferred until the *statement* is executed. – spencer7593 Jan 08 '18 at 23:02
  • get rid of the single quotes around the bind placeholders in the SQL text. Enclosed in single quotes, those will be interpreted as string literals, not bind placeholders, and `bindValue` is (likely) going to throw an error when it can't find a matching placeholder. – spencer7593 Jan 08 '18 at 23:28
  • Yeah, that fixed it. thanks for the help guys. – Rosco verheij Jan 08 '18 at 23:30

0 Answers0