Jump to content

Increasing effenciacy


sunziun

Recommended Posts

Hello,

I am new here and try to to learning PHP by doing.

 

This code is in use for now and growing:

 

$id=$_POST['id'];

 

$fname=$_POST['fname'];

$lname=$_POST['lname'];

$dob=$_POST['dob'];

$notes=$_POST['notes'];

$class=$_POST['class'];

 

$sql="UPDATE $table SET

        fname='$fname', lname='$lname', notes='$notes', dob='$dob',

        class='$class'

        WHERE id='$id'";

 

What is required to have the above code like this?:

 

$input_arr = array();

foreach ($_POST as $key => $input_arr) {

$_POST[$key] = addslashes($input_arr);

}

 

You see how small this is and its very effective

Link to comment
https://forums.phpfreaks.com/topic/240699-increasing-effenciacy/
Share on other sites

What exactly do you mean "what is required?" the code you provide will work much the same as your first code, however the function addslashes() requires its parameter to be a string, not an array as you are trying to use.. Why exactly would you rather write it the second way? I personally would prefer the first way, much easier to distinguish between values

do you mean you wish to dynamically create the query string based on whatever is posted? (assuming that $_POST[$key] has the same name as your database fields) ?

 

$string = '';
foreach ($_POST as $key => $value) {
$string .= $_POST[$key] ." = '".addslashes($value)."', ";
}

 

then you'll just need to strip the last comma off the string.

I was thinking of something like this:

 

$fn_sql="SELECT * FROM $table";

$fn_result=mysql_query($fn_sql);

 

while($fn=mysql_fetch_field($fn_result)){

    eval('$' . $fn->name . '=$_POST["' . $fn->name . '"];');

}

 

this is working perfect.

 

for an update query i need the second which contains fname='$name', lname='$lname' etc... to be generated automaticly like above.

It is just a terrible idea to use eval() like that, if you were getting some PHP syntax from your form fields by the user, all that code would be ran on your php server that the user wrote. There might be some VERY RARE situations why to use eval, but one should try to avoid it. For more info, google "eval is bad" or "eval is bad php". And eval() is also slow, so if you want to increase efficiency, last thing is to use eval().

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.