数组在php中没有按预期工作

时间:2016-05-12 15:00:19

标签: php mysql

我遇到了一个非常奇怪的问题。

我有一个函数可以从MySql打印给定数据库表的列名。

function getColoumn() {

    //replace it with your host normally it could be localhost
    $hostname='localhost';
    //mysql user name
    $username='admin_datauser';
    //mysql user password
    $password='iCoq4KrJM8';
    //connect to the mysql server
    $ss = mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);
    //select a database on the mysql server
    //please change as you like the database name
    mysql_select_db('admin_data');

    //SHOW COLUMNS FROM TABLENAME
    $query=mysql_query('SHOW COLUMNS FROM user') or die(mysql_error());


    foreach($fields as $key=>$field){
    echo '"'.$field->Field.'", '; // print each field name

    }
}   

输出如下所示 -

"id", "first_name", "last_name", "email", "address", "country", "city", "state", "phone_number", "fax", "image", "datecreated", "dateupdated", "Company", "token", 

我有另一个数组变量,其中当前的静态值如下所示 -

$searchArray = array("first_name","last_name","email","address","country","city","state","phone_number","fax","image");

我需要在$ searchArray中使用函数的变量。我尝试在arrya中调用变量,但它不起作用。

请帮忙吗?

1 个答案:

答案 0 :(得分:1)

首先,您不应再使用mysql_函数,因为它们已被弃用并且易于进行SQL注入。而是使用PHP自己的PDOmysqli库。

然后在foreach循环中直接将元素添加到数组中会更容易:

$searchArray = array();

foreach($fields as $key=>$field){
    $searchArray[]= $field->Field;
}

注意: PHP中的[]=运算符与+=运算符类似。但它不是添加数字值,而是将元素添加到数组中。