Posts Tagged with php function

Displaying 1-1 of 1 result.
Wiki: PHP file with array with key value from MySQL table columns generator functionwiki
posted by admin on April 18, 2017

public function array_from_table_generator($table, $id, $name, $prefix = 'tbl_'){
try
{
$sql = "SELECT t.".$id.", t.".$name." FROM ".$prefix.$table. " t ORDER BY t.id DESC";
// it is select query by mysql query or mysqli or by your way
/* $results = SELECT($sql); */ //change this field by your SELECT and
// end of select query
$string = '';
$filename = '../array/'.$table.'.php';

$string .= '<?php $array = '.PHP_EOL.'array('.PHP_EOL;
foreach($results as $key => $value){
$string .= chr(9).'"' . $value[$name] . '" => ' . $value[$id] . ','.PHP_EOL;
}
$string = rtrim(trim($string),',');
$string .= PHP_EOL.');';

$handle = fopen($filename, 'w');
fwrite($handle, $string);
fclose($handle);
echo $prefix.$table . " array generated successfully!
";
}catch ( Exception $e ) {
// send error message if you can
}
}

Usage:

array_from_table_generator('device', 'id', 'name');

Result:
device.php

<?php $array =
array(
"mobile device" => 2,
"desktop" => 1
);
Read more