简体   繁体   中英

How to insert an array using PHP to SQL Server Database

I want to insert an array as values on the SQL Server database using PHP. This is my code:

   $data = array(
  'score' => filter_input(INPUT_POST, 'score', FILTER_VALIDATE_INT),
  'max_score' => filter_input(INPUT_POST, 'maxScore', 
   FILTER_VALIDATE_INT),
  'opened' => filter_input(INPUT_POST, 'opened', FILTER_VALIDATE_INT),
  'finished' => filter_input(INPUT_POST, 'finished', 
   FILTER_VALIDATE_INT),
  'time' => filter_input(INPUT_POST, 'time', FILTER_VALIDATE_INT)
    );

   $data['user_id'] = $_SESSION['ex_uid'];

   $data['content_id'] = $content_id;


   $sql = "INSERT INTO results (content_id, user_id, score, max_score, opened, finished, time) 
     VALUES ($data)";
   $params = array(1, "some data");
   $stmt = sqlsrv_query( $connmssql, $sql, $params);

Always try to use parameterized statements. Function sqlsrv_query() does both statement preparation and statement execution, and can be used to execute parameterized queries. In your case you need to place one placeholder ? for each item in the $params array:

<?php

...
// Parameters
$score     = filter_input(INPUT_POST, 'score', FILTER_VALIDATE_INT);
$max_score = filter_input(INPUT_POST, 'maxScore', FILTER_VALIDATE_INT);
$opened    = filter_input(INPUT_POST, 'opened', FILTER_VALIDATE_INT);
$finished  = filter_input(INPUT_POST, 'finished', FILTER_VALIDATE_INT);
$time      = filter_input(INPUT_POST, 'time', FILTER_VALIDATE_INT);
$user_id   = $_SESSION['ex_uid'];

// Prepare and execute statement     
$params = array($score, $max_score, $opened, $finished, $time, $user_id, $content_id);  
$sql = "
    INSERT INTO results (score, max_score, opened, finished, time) 
    VALUES (?, ?, ?, ?, ?, ?, ?)
";
$stmt = sqlsrv_query($connmssql, $sql, $params);
if ($stmt === false) {  
    echo "Row insertion failed.\n";  
    die(print_r(sqlsrv_errors(), true));  
} else {  
    echo "Row successfully inserted.\n";  
} 

... 
?>
// Get only values // You must be sure that your data in the same order that your SET keys in the sql string $values = array_values($data); // Wrap with quotes $values = array_map(function ($value) { return '"' . $value . '"'; }, $values); $sql = "INSERT INTO results (score, max_score, opened, finished, time) VALUES (" . implode(',', $values) . ")";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM