简体   繁体   中英

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)."')");

也许您应该创建一个包含文件来执行$ gettables的值,然后它包含您希望获取$ gettables值的位置。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM