0

I have a MySQL statement that I want to execute and inside this statement I would like to include a for loop to define the columns that data will be entered into etc.

The code I currently have is

$stmt = $conn->prepare('INSERT into DATA ('.
    for($i = 0; $i < count($columns); $i++) {
        echo $columns[$i];
    }
    .') VALUES ('.
    for($i = 0; $i < count($columns); $i++) {
       echo ':'.$columns[$i].' , ';
    }
    .')');

Obviously this doesn't work but if it was to work also in the second for statement it echos a comma at the end of each loop, which will cause an error for the last loop so also is there a way to fix this to?

Thanks in advance!

4

3 回答 3

3

使用join/implode函数:

$params = array_map(function($var){return ':'.$var;}, $columns);
$sql = 'INSERT into DATA ('.join(',', $columns).') VALUES ('.join(',', $params).')';    
$stmt = $conn->prepare($sql);
于 2013-08-19T09:20:22.477 回答
1

使用implode的另一种方法:

$sql = "INSERT into DATA (`"  . implode('`,`', $columns) . "`) values (:" . implode(',:', $columns) . ")"
$stmt = $conn->prepare($sql);

示例结果:

// Input array
$columns = array('A', 'B', 'C');

// Output
INSERT into DATA(`A`,`B`,`C`) values (:A,:B,:C)
于 2013-08-19T09:26:43.777 回答
0

您应该在 prepare() 函数之外创建查询以使其更容易。

这样的事情会更好/更清晰:

$count = count ($columns); // Avoid using count in your loop init (Performances)
$query = 'INSERT INTO DATA (' .
for($i = 0; $i < $count; $i++) {
    $query .= $columns[$i];
}
$query .= ') VALUES (';
for($i = 0; $i < $count; $i++) {
   if ($i != $count - 1) $query.= ':'.$columns[$i].' , ';
   else $query .= ':'.$columns[$i]; // No coma for the last value
}
$query .= ')';
$stmt = $conn->prepare($query);
于 2013-08-19T09:25:54.297 回答