i allready found some answers at other topics but not a working answer for my situation. I'm having some troubles with inserting elements of an array into my DB. (SQL Server). When using a foreach loop in PHP the loop only inserts last element of the array into db, but when i printr($arrayname)
it shows the correct both elements.
Here's some of the code.
First i do a select to assign some variables: (the subquery is for removing ',' in the select)
$sql="SELECT ... FROM ...";
$query = sqlsrv_query( $conn, $sql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
}
$sql=substr($sql, 0, -1).")";
if ($query){
while($row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC) ) {
$variable=$row['rowname'];
}
}
So far so good, did an echo on the $variable
to test if it prints both row records, and it did.
Than i do the INSERT:
foreach($_SESSION['cart'] as $id => $value) {
print_r($id);
$sql="INSERT INTO() ... VALUES ('$value')";
$query= sqlsrv_query( $conn, $sql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
}
Here's where it goes wrong, again i did a print($id)
to test and see the values. It prints both values but only inserts the last element ( $variablename
) of array $id
.
Please, what am i doing wrong?
Cheers.
foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
}
$sql=substr($sql, 0, -1).")";
$query = sqlsrv_query( $conn, $sql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
if ($query){
while($row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC) ) {
$variable=$row['rowname'];
$sql2="INSERT INTO ()";
$stmt= sqlsrv_query( $conn, $sql2, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
}
}
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.