开发者

PHP MYSQL 'INSERT INTO $table VALUES ......' variable number of fields

I am still learning PHP and MYSQL and trying to make a program to list all tables and data in database (that's done), edit selected row (that's done) and now add new record on selected table. Now the problem is with variable number of fields. Table could be with 3 fields, could be 4 and so on. On my code here $getValue is an array. I am printing it out only for testing. It could look like "Array ( [name] => Tomas [lastName] => Timas )" or "Array ( [stufName] => Phone [stufPrice] => 58 [comments] => My new phone )" $getTable returns name of a table to insert into. This has to be a new record on the table, so stufID or nameID or what ever ID will be NULL How do I use "INSERT INTO table VALUES (value1, value2, value3,...)" if I do not know the number of values?

    <?php

include "conf.ini"; //connection to the db

$getValue=$_REQUEST['value'];
$getTable=$_REQUEST['table'];

// test********************
print_r($getValue);
print '<br>';
print $getTable;
// test********************

if (!$_POST['submit']) {
    print 'Please input data';
} else {

    mysql_query ("INSERT INTO $getTable VALUES (?????)"开发者_开发知识库);
}

?>


I hope you know this is very dangerous, so do this only if you're sure there are no potentional attackers!

$all_keys = array_keys($getValue);
$getValue = array_map('mysql_real_Escape_string', $getValues);
mysql_query ("INSERT INTO $getTable (`".implode('`,`', $all_keys)."`) VALUES ('".(implode(",", $getValue))."')");


$values = array_map('mysql_real_escape_string', array_values($getValue));
$keys = array_keys($getValue);        
mysql_query("INSERT INTO $getTable (".implode(',', $keys).") VALUES ('".implode('\',\'', $values)."')");


Perhaps you should create an include file to execute the values for $gettables and then it include that where you want $gettables values to be picked up.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜