Forum Moderators: coopster
I did it because I don't really know how the tables will end up, they aren't really finalized at the moment. So I wanted to be able to add whatever I wanted and not have big chunks of code for each select box that I needed to make.
$q1 = array("select table1_id,colname from table1","table1");
$q2 = array("select table2_id,colname from table2","table2");
$q3 = array("select table3_id,colname from table3","table3");
$cnt = 1;
while (isset(${'q' . $cnt})) {
$q = ${'q' . $cnt}[0];
$query = mysql_query($q);
$varn = ${'q' . $cnt}[1];
$$varn = '';
$$varn .= '<select name="' . $varn . '">' . "\n";
$$varn .= '<option value="">-- Pick One --</option>' . "\n";
while ($row = mysql_fetch_array($query)) {
$$varn .= '<option value="' . $row[0] . '">' . $row[1] . '</option>' . "\n";
}
$$varn .= "</select>\n";
$cnt++;
}
then I just had to output them later in the form using
<?= $table1?>
<?= $table2?>
<?= $table3?>
I could have done a looping way for output or used a control array to store the varnames but the form elements are all disorganized at the moment, just need an admin form for something. This way I can just add a 2 field query for the next table if I add one, simple enough.
just thought it was interesting and I love using variable variables (and variable variable names) for making my life easier
anyone have any other little tricks or think they can make my script better or more interesting?
I have an admin page wherein I put up select box for database name, then table, then list the fields of the table with checkboxes. Once fields are checked off, it generates the html for the form and the php needed to process the form and displays it all on the page. Then I just copy & paste into editor. It's about 300 lines long but I'm not scared to post it if someone wants me to.
This one I like, although it doesn't use variable variables. It's a generic insert routine that's part of my database class. You hand it the name of the table and associative array of field names & values, and it compiles & executes the INSERT. It calls a function called opendb() which is self-explanatory. It also uses a function called 'fixup()' which just returns a string surrounded by single quotes or NULL (alphanumeric, suitable for the SQL statement) if the string is empty. I have one that's very similar called udary(). You additionally pass it the WHERE clause for the update.
/** Insert by array, $ary['fieldname'] => $val */
function insary($tname,$ary){
if($this->linkID === false){
if(($this->linkID = $this->opendb()) === false)
return false;
$opened = 1;
}
else $opened = 0;
if($rflds = mysql_query("SELECT * FROM $tname",$this->linkID)) {
$nf = mysql_num_fields($rflds);
for($i = 0; $i < $nf; $i++){
$fldspec = mysql_fetch_field($rflds,$i);
$ftype[$fldspec->name] = $fldspec->numeric;
$nulls[$fldspec->name] = ($fldspec->not_null == 1)? 0 : 1;
}// EndFor get field type for each field
}// EndIf got query
else {
$rflds = $this->list_fields($tname,true);
foreach($rflds as $fldinfo) {
$fldspec = implode(",",$fldinfo);
list($a,$b) = explode(":",$fldspec[ 0 ]);
list($c,$d) = explode(":",$fldspec[ 1 ]);
list($e,$f) = explode(":",$fldspec[ 2 ]);
if((strpos($d,"varchar")!== false) ¦¦ (strpos($d,"text")!== false))
$ftype[$b] = 0;
else
$ftype[$b] = 1;
$nulls[$b] = ($f == '')? 1 : 0;
}// EndForEach field
}// EndElse get field names a different way
$sqltext = "INSERT INTO $tname (";
$vtext = ") values (";
foreach($ftype as $fldname => $fldtype) {
if(isset($ary[$fldname])) {
$fldval = $ary[$fldname];
$sqltext .= "$fldname,";
if($fldtype)
$vtext .= "$fldval,";
else {
$this->fixup($fldval);
if(($fldval == "NULL") && ($nulls[$fldname] == 0))
$fldval = "''";
$vtext .= $fldval . ",";
}
}// If this field value is in array
}// EndForEach field
$sqltext = substr($sqltext,0,-1);
$vtext = substr($vtext,0,-1) . ")";
$sqltext .= $vtext;
mysql_query($sqltext,$this->linkID);
$rtn = mysql_insert_id($this->linkID);
$this->insertID = $rtn;
mysql_free_result($rflds);
if($opened){
mysql_close($this->linkID);
$this->linkID = false;
}// EndIf opened db here
return $sqltext;
}// End insary()
[edited by: jatar_k at 12:12 am (utc) on Jan. 27, 2007]
[edit reason] fixed formatting [/edit]
that actually reminds me that we haven't had a tips and tricks thread in a while
thread title changed and here are the previous ones, all great reads
PHP Bag of Tricks I [webmasterworld.com]
PHP Bag of Tricks II [webmasterworld.com]
PHP Bag of Tricks III [webmasterworld.com]
Good PHP solutions to small problems [webmasterworld.com]
feel free to recommend any great threads you use for common solutions as well
<?
class CheckText
{
var $badWords;
// BAD WORDS FILTER
function CheckText()// constructor
{
$badWords = array(
'aaaaa',
'sssss',
'dddddd',
'fffff',
'ggggg');
$this->badWords=array();
srand ((float)microtime()*1000000);
$censors=array ('$','@','#','*','£','^','!','~');
foreach ($badWords as $badWord) {
$badWord = preg_quote($badWord);
$replaceStr='';
$size=strlen($badWord);
for ($i=0;$i<$size;$i++) {
shuffle($censors);
$replaceStr.=$censors[0];
}
$this->badWords[$badWord]=$replaceStr;
}
} //end WordFilter
function filter ($text) {
foreach ($this->badWords as $badWord => $replaceStr) {
$text=preg_replace('/'.$badWord.'/i',$replaceStr,$text);
}
return $text;
} //end filter
// END BAD WORDS FILTER
// using it
// "name" Bad words filter
// $text is class function WorldFilter var
$wordFilter=new CheckText($badWords);
$text=$bw;
$text = $wordFilter->filter($text);
if
($text!==$bw)
{
echo "<h3> The submitted name $text contains vulgar words.</h3><a href=\"../insert/zzzzzzz.php\">
<b>Please, CLEAN and re-enter a proper Name</b></a><p>";
}
// ends "name" bad words filter
<?php
function isValidInteger($i)
{
return (is_numeric($i) && !preg_match('/[[:^digit:]]/', $i) ? true : false);
}
$pwdmin = 8; // Minimum password length
$pwdlen = (isset($_POST['pwdlen']) && isValidInteger($_POST['pwdlen'])) ? $_POST['pwdlen'] : $pwdmin;
$pwdnum = (isset($_POST['pwdnum']) && isValidInteger($_POST['pwdnum'])) ? $_POST['pwdnum'] : '';
?>
<html><head><title>Password Generator</title></head><body>
<fieldset>
<legend>Password Generator</legend>
<form action="<?php print strip_tags($_SERVER['REQUEST_URI']);?>" method="post">
<label>Password Length: <input type="text" name="pwdlen" value="<?php print $pwdlen; ?>"></label>
<label>Number to Generate: <input type="text" name="pwdnum" value="<?php print $pwdnum; ?>"></label>
<input type="submit" name="submit" value="submit">
</form>
</fieldset>
<?php
if ($pwdlen < $pwdmin) {
print "Password length must be greater than or equal to $pwdmin.";
}
if (!$pwdnum) {
print "You must specify how many passwords to generate.";
}
if (isset($_POST['submit']) && $pwdlen && $pwdnum) {
$alpha = array_merge(range('a', 'z'), range('A', 'Z'));
for ($p = 0; $p < $pwdnum; $p++) {
$pwds[] = substr($alpha[array_rand($alpha)] .
substr_replace(md5(uniqid(mt_rand(), true)),
$alpha[array_rand($alpha)], 3, 1), 0, $pwdlen);
}
print '<pre>' . implode("\n", $pwds) . '</pre>';
}
?>
</body></html>
Once TJ and me had a
“small conversation” about rand [webmasterworld.com]
<?php
function compress( $srcFileName, $dstFileName )
{
// getting file content
$fp = fopen( $srcFileName, "r" );
$data = fread ( $fp, filesize( $srcFileName ) );
fclose( $fp );
// writing compressed file
$zp = gzopen( $dstFileName, "w9" );
gzwrite( $zp, $data );
gzclose( $zp );
}
function uncompress( $srcFileName, $dstFileName, $fileSize )
{
// getting content of the compressed file
$zp = gzopen( $srcFileName, "r" );
$data = fread ( $zp, $fileSize );
gzclose( $zp );
// writing uncompressed file
$fp = fopen( $dstFileName, "w" );
fwrite( $fp, $data );
fclose( $fp );
}
?>
<?
compress( "check.test.php", "check.test.php.gz" );
uncompress( "check.test.php.gz", "check.test.php", filesize( "check.test.php" ) );
?>
Don't know where that one comes from :)
This is another from my database class and isn't startling in any way but I sure do find it handy.
$dbt is the table name and $dbw is the WHERE clause
$dbf is kind of slick because you can set it to a single field name, a comma delimited list of fields, or an array:
$dbf = 'firstname';
$dbf = 'firstname,lastname';
$dbf = array('firstname','lastname','city','state');
if $dbf is a single field name, the function returns a scalar result. If it's multiple field names in either of the above forms or '*', the function returns an associative array. If there's a problem with the query or no rows match, it returns false.
function bring($dbt,$dbf,$dbw){
if($this->linkID === false){
if(($linkID = $this->opendb()) === false)
return false;
$opened = 1;
}
else $opened = 0;
if(is_array($dbf))
$flds = implode(",",$dbf);
else
$flds = $dbf;
if(($qry = mysql_query("SELECT $flds FROM $dbt $dbw",$this->linkID)) === false){
if($opened){
mysql_close($this->linkID);
$this->linkID = false;
}// EndIf opened db here
return false;
}// EndIf query invalid
if(mysql_num_rows($qry)){
$rtn = mysql_fetch_array($qry,MYSQL_BOTH);
if((!is_array($dbf)) && (strpos($dbf,",") === false) && ($dbf!= '*'))
$rtn = $rtn[0];
}// EndIf have data
else
$rtn = false;
mysql_free_result($qry);
if($opened){
mysql_close($this->linkID);
$this->linkID = false;
}// EndIf opened db here
return $rtn;
}// End bring()
Nothing fancy, but simplifies little things like:
echo 'Welcome back ' . $db->bring('users','firstname',"WHERE RecID=$recID");