Last foreach change

3 posts by 2 authors in: Forums > CMS Builder
Last Post: March 17, 2023   (RSS)

By AlanAlonso - March 16, 2023 - edited: March 16, 2023

I made a form using a multirecord table, post and echo post data is correct but I have a problem changing last digit of the foreach need to be ;  not  , but just for the last to generate the INSERT INTO for mysql, any suggestion?

<?php foreach ($asignaturasRecords as $record): ?>
      <?php $num = $record['num']; ?>
	  <?php echo "('" . $_POST["createdDate_$num"] . "',"; ?>
	  <?php echo "'" . $_POST["createdByUserNum_$num"] . "',"; ?>
	  <?php echo "'" . $_POST["updatedDate_$num"] . "',"; ?>
	  <?php echo "'" . $_POST["updatedByUserNum_$num"] . "',"; ?>
	  <?php echo "'" . $_POST["curp_$num"] . "',"; ?>
	  <?php echo "'" . $_POST["claveasignatura_$num"] . "',"; ?>
	  <?php echo "'" . $_POST["ciclo_$num"] . "',"; ?>
	  <?php echo "'" . $_POST["calificacion_$num"] . "',"; ?>
	  <?php echo "'" . $_POST["idobservaciones_$num"] . "'),"; ?>
<?php endforeach ?>

('2023-03-16 03:31:12', '1', '2023-03-16 03:31:12', '1', 'TFAR960722HDFESD10', 'LP946', '2020', '9.4', '100'),
('2023-03-16 03:31:12', '1', '2023-03-16 03:31:12', '1', 'TFAR960722HDFESD10', 'LP947', '2020', '9.4', '100'),
('2023-03-16 03:31:12', '1', '2023-03-16 03:31:12', '1', 'TFAR960722HDFESD10', 'LP948', '2020', '9.4', '100'),
('2023-03-16 03:31:12', '1', '2023-03-16 03:31:12', '1', 'TFAR960722HDFESD10', 'LP499', '2020', '9.4', '100'),
('2023-03-16 03:31:12', '1', '2023-03-16 03:31:12', '1', 'TFAR960722HDFESD10', 'LP950', '2020', '9.4', '100'),

UPDATE
--------------------
I was trying to use str_replace or substr_replace but does not work, I get that doesn't work as the value is an array.
Also tried

foreach ($asignaturasRecords as $record => $element) {
    if ($record === array_key_first($array)) {
        echo "'" . $_POST["idobservaciones_$num"] . "'),";
    }

    if ($record === array_key_last($array)) {
        echo "'" . $_POST["idobservaciones_$num"] . "');";
    }
}

Solved

By Dave - March 17, 2023

Hi Alan,

Glad you got it working!  If you're inserting form data into MySQL be sure to escape your inputs.  We have a helper function mysql_escape() for that.  

Dave Edis - Senior Developer
interactivetools.com