PHP MYSQL'INSERT INTO $ table VALUES ......'可变字段数 [英] PHP MYSQL 'INSERT INTO $table VALUES ......' variable number of fields

查看:151
本文介绍了PHP MYSQL'INSERT INTO $ table VALUES ......'可变字段数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在学习PHP和MYSQL,并尝试制作一个程序来列出数据库中的所有表和数据(已完成),编辑选定的行(已完成),现在在选定的表上添加新记录.现在,问题出在可变数量的字段上.表可以有3个字段,可以是4个,依此类推.在我的代码中,$ getValue是一个数组.我仅将其打印出来以进行测试.它看起来像是数组([name] => Tomas [lastName] => Timas")或数组([stufName] => Phone [stufPrice] => 58 [comments] =>我的新手机") $ getTable返回要插入的表的名称. 这必须是表上的新记录,因此stufID或nameID或任何ID都将为NULL 如果我不知道值的数量,如何使用"INSERT INTO table VALUES(value1,value2,value3,...)"?

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 (?????)");
}

?>

推荐答案

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

这篇关于PHP MYSQL'INSERT INTO $ table VALUES ......'可变字段数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆