Database > MySQL database

calculation in mysql query

(1/1)

infomamun:
Hi there,
I want to insert value from calculation in mysql query. How to do that?

for example:

--- PHP Code: ---$table = $Post['table'];
$array = (100,200,300,400,500);
$value = explode(',',$array);
$limit = count($value);
$counter = 1;
//........Connection string
while($counter<=$limit){
mysql_query("INSERT INTO $table (amount1, amount2) Values($value[$counter],$value[$counter+1])")
$counter=$counter+1;
}
--- End code ---

In the above example table name in mysql query will be derived from a post value of a html form. Value of respective column of mysql table will be derived from explode value.
My question is how to write proper sql query string so that variable name (like $table) and calculation ($value[$counter+1]) will be executed in the sql query?
(like "INSERT INTO".$table."(amount1,amount2).....")

Any help will be appreciated.

Thanks in advance

Vision Hive:
You didn't test that code before you posted...
1. $array = (100,200,300,400,500); will result in a parse error. Initialize arrays using $a=array(1,2,3);
2. You don't explode arrays, it doesn't make sense. explode() is used to split a string into an array.
3. $Post is not a pre-populated PHP variable. Use $_POST
4. Arrays in PHP are 0-indexed, so if you set $counter=1 you will skip over the first entry
5. The notion of allowing someone to modify a database by passing the table name in a form field is riddled with security issues and is generally a terrible idea.
6. You cannot hard-code the query because you don't know the field names in the table that is being accessed. You would need to do a DESCRIBE 'tablename' query first, and then match the field names to the $_POST data
7. The notion of allowing someone to modify a database by passing the table name in a form field is riddled with security issues and is generally a terrible idea.

cabalsdemon:
are you trying to add the valuse of a b c d and e

and to call that an array you need to specify


--- PHP Code: ---
array (100,200,300,400,500)



--- End code ---


not

--- PHP Code: ---
$array = (100,200,300,400,500);



--- End code ---

richei:
no, actually its
--- PHP Code: ---$array = array(100,200,300,400,500);
--- End code ---


hive, while you're right on the security issues, you don't know where the input is coming from, it could be a listing of the available tables, unless i missed something in his first post.

Navigation

[0] Message Index

Go to full version