Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert array into MySQL when varchar must be inserted

See the image here I have a form that collects info of: year(int), Case number(varchar) and Time received(varchar). Since year is a number, I set int in MySQL, then Case number and Time Received has both numbers and letters therefore I had set varchar in MYSQL. I used array because I insert a lot of records. Im using mysql_real_escape_string() for the array. But it did not work. How can I pass the array which has letters, symbols, and numbers to insert into MySQL? Thank you.

//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
if (isset($_REQUEST['submit']) && isset($_REQUEST['year']) ) {
  foreach ($_REQUEST['year'] as $k=> $value ){ // loop through array

    $year     = $_REQUEST['year'];
    $c_no        = mysql_real_escape_string($_REQUEST['cs']);
    $t_r        = mysql_real_escape_string($_REQUEST['t_r']);


$mysqli->query("INSERT INTO firearms_id_secs (year, case_no, t_received) VALUES 
   ($year[$k], $c_no[$k], $t_r[$k])");
}
}
?>

This is the HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Add more fields using jQuery</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" name="year[]" value="" placeholder="Year"/><input type="text" name="cs[]" value="" placeholder="Case no"/><input type="text" name="t_r[]" value="" placeholder="Time Received"/><a href="javascript:void(0);" class="remove_button" title="Remove field"><img src="remove-icon.png"/></a></div>'; //New input field html 
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
    if(x < maxField){ //Check maximum number of input fields
        x++; //Increment field counter
        $(wrapper).append(fieldHTML); // Add field html
    }
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
    e.preventDefault();
    $(this).parent('div').remove(); //Remove field html
    x--; //Decrement field counter
    });
});
</script>
<style type="text/css">
input[type="text"]{height:20px; vertical-align:top;}
.field_wrapper div{ margin-bottom:10px;}
.add_button{ margin-top:10px; margin-left:10px;vertical-align: text-bottom;}
.remove_button{ margin-top:10px; margin-left:10px;vertical-align: text-    bottom;}
</style>
</head>
<body>
<form name="codexworld_frm" action="" method="post">
<div class="field_wrapper">
<div>

        <a href="javascript:void(0);" class="add_button" title="Add field"><img     src="add-icon.png"/></a>
</div>
</div>
<input type="submit" name="submit" value="SUBMIT"/>
</form>
</body>
</html>
like image 933
RumRum Avatar asked Mar 01 '26 21:03

RumRum


1 Answers

When the form is submitted _POST (or _REQUEST) will look like this

array (
  'year' => 
  array (
    0 => '2001',
    1 => '2010',
  ),
  'cs' => 
  array (
    0 => '1',
    1 => '2',
  ),
  't_r' => 
  array (
    0 => '12:00:00',
    1 => '13:00:00',
  ),
  'submit' => 'SUBMIT',
)

It would be nicer if it looked like

array(
    'records' = array(
        0=>array('year'=>'2001', 'cs'=>'1', 't_r'=>'12:00:00'),
        0=>array('year'=>'2010', 'cs'=>'2', 't_r'=>'13:00:00'),
    ),
)

That would require changing the javascript code (and I'm too lazy for that right now...so I'm using the SPL MultipleIterator to "simulate" that data format)

if ( isset($_POST['submit']) ) {
    // add tests for is_array() POST[year], POST[cs] and POST[t_r]

    // this will make mysqli throw an exception whenever an operation results in an 
    // (mysql) error code other than 0 -> no further error handling included in this script....
    mysqli_report(MYSQLI_REPORT_ALL|MYSQLI_REPORT_STRICT);
    $mysqli = new mysqli('localhost', 'localonly', 'localonly', 'test');

    // create a prepared statement and bind the parameters, see http://docs.php.net/mysqli.quickstart.prepared-statements
    $stmt = $mysqli->prepare('INSERT INTO firearms_id_secs (year, case_no, t_received) VALUES (?,?,?)');
    if ( !$stmt->bind_param('sss', $year, $caseno, $time) ) { // binding all parameters as strings ...let mysql's type system handle it...
        yourErrorHandlerHere(); // or throw an exception....
    }
    // when ever the statement is executed, the current values (at _that_ moment) in $year, $caseno and $time will be used where the ? are in the statement

    // this wouldn't be necessary if the POST body looked like record[1][year]=2001&....
    $mit = new MultipleIterator;
    $mit->attachIterator( new ArrayIterator($_POST['year']) );
    $mit->attachIterator( new ArrayIterator($_POST['cs']) );
    $mit->attachIterator( new ArrayIterator($_POST['t_r']) );

    foreach( $mit as $record ) {
        echo 'executing statement with [', join(',', $record), "]<br/>\r\n";
        // assign the values to the bound parameters
        list($year,$caseno,$time) = $record;
        // and then execute the statement (with those values)

        /*
        you might want to wrap this in a try-catch block, so a single faulty record will not throw off your entire script.
        You might also want to look into transactions (in case a single faulty record is supposed to roll back the entire operation)
        see http://docs.php.net/language.exceptions , http://dev.mysql.com/doc/refman/5.7/en/commit.html
        */
        $stmt->execute();
    }
}

edit: a) To allow NULL values you should replace empty strings by NULL in the parameters

...
// replace empty strings by NULL
$record = array_map(
    function($e) {
        return 0<strlen(trim($e)) ? $e : NULL;
    },
    $record
);

// assign the values to the bound parameters
list($year,$caseno,$time) = $record;
...

b) I don't know why and where you would need the iterator's key in this scenario, but ....

<?php
$data=array(
    'maj'=>new ArrayIterator(array('A','B','C')),
    'min'=>new ArrayIterator(array('a','b','c')),
    'foo'=>new ArrayIterator(array('do'=>'re', 'mi'=>'fa', 'so'=>'la', 'ti')),
);

$mit = new MultipleIterator(MultipleIterator::MIT_NEED_ANY|MultipleIterator::MIT_KEYS_ASSOC);
$mit->attachIterator( $data['maj'], 'majuscule' );
$mit->attachIterator( $data['min'], 'minuscule' );
$mit->attachIterator( $data['foo'], 'lalala' );

foreach( $mit as $r ) {
    var_export($r);
}

prints

array (
  'majuscule' => 'A',
  'minuscule' => 'a',
  'lalala' => 're',
)array (
  'majuscule' => 'B',
  'minuscule' => 'b',
  'lalala' => 'fa',
)array (
  'majuscule' => 'C',
  'minuscule' => 'c',
  'lalala' => 'la',
)array (
  'majuscule' => NULL,
  'minuscule' => NULL,
  'lalala' => 'ti',
)
like image 96
VolkerK Avatar answered Mar 04 '26 11:03

VolkerK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!