I'm quite new at this and I'm having difficulties adding entries to an array.
The below is supposed to generate a batch of serial numbers and put it in two tables, but the code only generates 1 record in the array instead of the $volume number. I'm simply not getting the loop right (or something else). Can anybody please help.
Thanks,
Code: Select all
<?php
//create short variables
$customerid = $_POST['customerid'];
$volume = trim($_POST['volume']);
$labelspec1 = trim($_POST['labelspec1']);
$created = date (c);
$batchid = 'batchid';
//make sure you have the values
if (!$customerid || !$volume || !$labelspec1)
{
echo '<p>You haven\'t entered any customer details. Please go back and try agan.</p>';
exit;
}
//Test values
// echo $customerid.', '.$volume.', '.$labelspec1.'<br />';
//connect to the database
@ $db = new mysqli('xxxxx', 'xxxxx', 'xxxxx', 'xxxxx');
//create an errormessage if you couldn't connect to the database
if (mysqli_connect_errno())
{
echo '<p><strong>Error: </strong>Could not connect to database. Please try again late. Your record(s) has not been stored.</p>';
exit;
}
//create batch_array and write the values
$batch_array = array('batchid' => 'NULL', 'customerid' => $customerid, 'created' => $created, 'record_numbers' => $volume);
//Test values
//print_r($batch_array);
//create serials_array
$serials_array = array('recordnumer', 'batchid', 'serial', 'labelspec1');
//loop serials for the volume number
for ($add_record = 0; $add_record < $volume; $add_record++)
{
//generate a serial
function rand_string( $length )
{
$chars = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"; //excluding lowercase ilo, uppercase IO, and numbers 01
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ ) {
$str .= $chars[ rand( 0, $size - 1 ) ];
}
return $str;
}
$serial = rand_string( 16 );
//check if the serial exist in the database
$query = "select * from serials where serial = ".$serial." limit 1";
$result = $db->query($query);
$num_results = $result->num_rows;
//if query result is 0 (doesn't exit in database) write it to the array
if (!$num_results)
{
$serials_array = array('recordnumber' => 'NULL', 'batchid' => $batchid, 'serial' => $serial, 'labelspec1' => $labelspec1);
}
//Test values
foreach ($serials_array as $current) echo $current.', ';
}
?>